[英]compiling c and c++ files using g++
我正在尝试编译C和C ++文件并将它们链接在一起。 我正在关注此链接的答案- 使用GCC一起编译C和C ++文件
但是,我有一个不同的问题,该职位未对此进行解释。 我已经在C ++文件中定义了main(),并使用了一个函数,其详细信息在C文件中。 函数的声明在.h文件中,该文件同时包含在C和C ++文件中。
我的C ++文件-
#include<iostream>
#include<testc.h>
using namespace std;
extern "C" void cfunc(int, int);
int main()
{
cout<<"Hello from cpp"<<endl;
cfunc(3,6);
}
我的C档案-
#include<stdio.h>
#include<testc.h>
int cfunc2(int a, int b)
{
return a+b;
}
void cfunc(int a, int b)
{
printf("Hello from c %d\n",cfunc2(a,b));
}
我的.h文件-
int cfunc2(int, int);
void cfunc(int, int);
与其他帖子一样,如果我在C ++代码中使用C函数,则需要在C ++文件中提供以下定义-
extern "C" void cfunc(int, int);
但是,当我这样运行时,出现以下错误-
testcpp.cpp:6:17: error: conflicting declaration of ‘void cfunc(int, int)’ with ‘C’ linkage
extern "C" void cfunc(int, int);
In file included from testcpp.cpp:2:0:
inc/testc.h:9:6: note: previous declaration with ‘C++’ linkage
void cfunc(int, int);
我从main进行调用的地方是testcpp.cpp,testc.c包含函数定义,而testc.h是头文件。
我运行以下命令集-
gcc -c -std=c99 -o testc.o testc.c -Iinc
g++ -c -std=c++0x -o testcpp.o testcpp.cpp -Iinc
g++ -o myapp testc.o testcpp.o
inc文件夹包含.h文件
我做错了什么?
在.h
文件中声明了该函数之后,无需在C ++文件中提供该函数的另一声明(并且此文件从C ++中包含了,出现了)。 这是C ++编译器明显抱怨的地方,因为它们是不同的。
而是将声明包装在.h
文件中,如下所示:
#ifdef __cplusplus
extern "C" {
#endif
< your declarations go here >
#ifdef __cplusplus
}
#endif
或以相同方式将#include
行包装到.cpp
文件中:
extern "C" {
#include "testc.h"
}
这个想法是C和C ++部分将需要看到以不同方式声明的同一函数。 这就是为什么.h
文件中需要#ifdef
的原因,因为C和C ++都包含了该文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.