【问题标题】:Calling C function from C++ with same name从 C++ 调用具有相同名称的 C 函数
【发布时间】:2020-11-10 20:54:16
【问题描述】:

我已阅读此answer,但如果我在 C++ 和 C 中具有相同名称的两个函数,我不知道该怎么办。 C 函数已在头文件中使用 if #ifdef __cplusplus 进行保护。 所以我有 .cpp 文件

foo (int a, int b)
{
//calling from C
foo (int a, int b, int c)
}

Cheader.h

#ifdef __cplusplus
extern "C" {
#endif

void foo(int a,int b, int c);

#ifdef __cplusplus
}
#endif

文件.c

#include "Cheader.h"

void foo(int a,int b, int c)
{
    /* ... */
}

C++ 头文件

Cplusplusheader.hpp

void foo(int a, int b);

C++

CplusPlus.cpp

#include "Cplusplus.hpp"
#include "Cheader.h"

void foo(int a, int b)
{
    foo(a,b,c); // call C function
    // ...
}

【问题讨论】:

  • 您能否进一步解释一下您是如何从 C++ 调用 C 函数以及项目的结构?
  • 与参考答案相同
  • @HazemAbaza 这不是有用的信息
  • 问题是什么?检查C++ namespaces
  • 希望是一个明显的注释,但foo(int a, int b, int c) 不是对函数的调用:您可能指的是foo(a, b, 100); 之类的东西。请将您的代码更新为您遇到问题的实际代码,以便我们也可以尝试。

标签: c++ c


【解决方案1】:

好吧,我只是做了一个例子来测试它,你可以把它当作任何其他函数来调用。编译器似乎明白 C foo 只是 C++ foo 的重载。这是一个例子:

main.cpp

//main.cpp

#include <iostream>
#include "header.h"

//c++ foo
void foo(int num1, int num2)
{
    foo(num1);
    foo(num2);
    std::cout << "Sum: " << num1 + num2 << std::endl;
}

int main()
{
    foo(10, 10);
    return 0;
}

header.h

//header.h
#ifndef HEADER_H
#define HEADER_H
#include <stdio.h>
#include <stdlib.h>

#ifdef __cplusplus
extern "C"
{
#endif

//c foo
void foo(int number);

#ifdef __cplusplus
}
#endif
#endif

source.c

//source.c

#include "header.h"

//c foo
void foo(int number)
{
    printf("The number is: %i\n", number);
}

输出:

The number is: 10
The number is: 10
Sum: 20

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 2011-03-10
    • 2021-05-01
    • 2017-09-29
    • 1970-01-01
    • 2014-10-16
    相关资源
    最近更新 更多