Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/146.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
编译c和c++;使用g++; 我试图编译一个C和C++文件并把它们链接在一起。以下是本链接的答案:_C++_C_G++ - Fatal编程技术网

编译c和c++;使用g++; 我试图编译一个C和C++文件并把它们链接在一起。以下是本链接的答案:

编译c和c++;使用g++; 我试图编译一个C和C++文件并把它们链接在一起。以下是本链接的答案:,c++,c,g++,C++,C,G++,然而,我有一个不同的问题,那篇文章没有解释。我在C++文件中定义了我的Mead(),并使用了C文件中的细节。函数的声明在.h文件中,它包含在C和C++文件中。 我的C++文件-< /P> #include<iostream> #include<testc.h> using namespace std; extern "C" void cfunc(int, int); int main() { cout<<"Hello from cpp"<&

然而,我有一个不同的问题,那篇文章没有解释。我在C++文件中定义了我的Mead(),并使用了C文件中的细节。函数的声明在.h文件中,它包含在C和C++文件中。

我的C++文件-< /P>

#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++代码中使用C函数,我需要在C++文件中给出以下定义-< /p>

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);
testcpp.cpp是我从main进行调用的地方,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文件


<>我做的任何事情都是错的,

在C++代码中声明C++中的函数后,不需要提供另一个函数声明。这是C++编译器明确抱怨的,因为它们不同。

相反,可以将您的声明包装在
.h
文件中,如下所示:

 #ifdef __cplusplus
 extern "C" {
 #endif

 < your declarations go here >

 #ifdef __cplusplus
 }
 #endif

的思想是C和C++部分需要以不同的方式看到相同的函数。这就是为什么 H./Cux>文件中需要代码> > IFDEF < /C>,因为它包含了C和C++。P> > P>在C++代码中声明C++中的函数后,不需要提供另一个函数声明(并且从C++中包含这个文件,如它所示)。这是C++编译器明确抱怨的,因为它们不同。

相反,可以将您的声明包装在
.h
文件中,如下所示:

 #ifdef __cplusplus
 extern "C" {
 #endif

 < your declarations go here >

 #ifdef __cplusplus
 }
 #endif

的思想是C和C++部分需要以不同的方式看到相同的函数。这就是为什么 H./Cux>文件中需要代码> > IFDEF < /C>,因为它包含了C和C++。p>

extern“C”cfunc(int,int)中是否有输入错误?因为它应该是
extern“C”void cfunc(int,int)@IharobAlAsimi感谢您指出。已编辑请显示一个产生错误的代码示例。@code学徒在
extern“C”cfunc(int,int)中添加了一个输入错误?因为它应该是
extern“C”void cfunc(int,int)@IharobAlAsimi感谢您指出。已编辑请显示一个产生错误的代码示例。@code Peedint addedI使用了您提供的seconf修复程序,它成功了。谢谢我的回答听起来很粗鲁,应该用更好的措辞。我为此道歉!我用了你给我的seconf补丁,它成功了。谢谢我的回答听起来很粗鲁,应该用更好的措辞。我为此道歉!
 #ifdef __cplusplus
 extern "C" {
 #endif

 < your declarations go here >

 #ifdef __cplusplus
 }
 #endif
 extern "C" {
 #include "testc.h"
 }