Ray*_*yne 4 c c++ linux undefined-reference
我正在使用Linux,我有以下文件:
main.c, main.h
fileA.c, fileA.h
fileB.cpp, fileB.h
Run Code Online (Sandbox Code Playgroud)
该函数F1()在中声明fileB.h并定义fileB.cpp.我需要使用函数fileA.c,所以我将函数声明为
extern void F1();
Run Code Online (Sandbox Code Playgroud)
在fileA.c.
但是,在编译期间,我收到了错误
fileA.c: (.text+0x2b7): undefined reference to `F1'
Run Code Online (Sandbox Code Playgroud)
怎么了?
谢谢.
ETA:感谢我收到的答案,我现在有以下内容:
在fileA.h中,我有
#include fileB.h
#include main.h
#ifdef __cplusplus
extern "C"
#endif
void F1();
Run Code Online (Sandbox Code Playgroud)
在fileA.c中,我有
#include fileA.h
Run Code Online (Sandbox Code Playgroud)
在fileB.h中,我有
extern "C" void F1();
Run Code Online (Sandbox Code Playgroud)
在fileB.cpp中,我有
#include "fileB.h"
extern "C" void F1()
{ }
Run Code Online (Sandbox Code Playgroud)
但是,我现在有错误
fileB.h: error: expected identifier or '(' before string constant
Run Code Online (Sandbox Code Playgroud)
Lig*_*ica 15
如果您真的编译fileA.c为C而不是C++,那么您需要确保该函数具有正确的C兼容链接.
您可以使用extern关键字的特殊情况来执行此操作.声明和定义:
extern "C" void F1();
extern "C" void F1() {}
Run Code Online (Sandbox Code Playgroud)
否则,C链接器将查找仅存在一些受损的C++名称和不受支持的调用约定的函数.:)
不幸的是,虽然这是你在C++中必须做的,但语法在C中无效.您必须extern只对C++代码可见.
所以,有了一些预处理器的魔力:
#ifdef __cplusplus
extern "C"
#endif
void F1();
Run Code Online (Sandbox Code Playgroud)
不完全漂亮,但这是你在两种语言的代码之间共享标题所付出的代价.
为了能够从c源代码调用c ++函数,你需要给出适当的linkage specification.
指定链接规范的格式是
extern "type_of_Linkage" <function_name>
Run Code Online (Sandbox Code Playgroud)
所以在你的情况下,你应该使用:
extern "C" void F1();
Run Code Online (Sandbox Code Playgroud)