我正在使用Linux,我有以下文件:
main.c, main.h
fileA.c, fileA.h
fileB.cpp, fileB.h
函数F1()
在fileB.h
中声明,并在fileB.cpp
中定义。我需要使用fileA.c
中的函数,因此我将函数声明为
extern void F1();
fileA.c
中的。
然而,在编译期间,我收到了错误
fileA.c: (.text+0x2b7): undefined reference to `F1'
有什么问题?
谢谢。
ETA:感谢我收到的答案,我现在有以下内容:
在fileA.h中,我有
#include fileB.h
#include main.h
#ifdef __cplusplus
extern "C"
#endif
void F1();
在fileA.c中,我有
#include fileA.h
在fileB.h中,我有
extern "C" void F1();
在fileB.cpp中,我有
#include "fileB.h"
extern "C" void F1()
{ }
但是,我现在有错误
fileB.h: error: expected identifier or '(' before string constant
答案 0 :(得分:15)
如果您真的将fileA.c
编译为C而不是C ++,那么您需要确保该函数具有正确的C兼容链接。
您可以使用extern
关键字的特殊情况执行此操作。声明和定义都是:
extern "C" void F1();
extern "C" void F1() {}
否则,C链接器将查找仅存在一些受损的C ++名称和不受支持的调用约定的函数。 :)
不幸的是,虽然这是您在C ++中必须做的事情,the syntax isn't valid in C。您必须使extern
仅对C ++代码可见。
所以,使用一些预处理器魔术:
#ifdef __cplusplus
extern "C"
#endif
void F1();
不完全漂亮,但这是你在两种语言的代码之间共享标题所付出的代价。
答案 1 :(得分:5)
为了能够从c源代码调用c ++函数,你需要提供适当的linkage specification
。
指定链接规范的格式为
extern "type_of_Linkage" <function_name>
所以在你的情况下,你应该使用:
extern "C" void F1();
答案 2 :(得分:4)
也许,使用
extern "C" void F1();
答案 3 :(得分:2)
fileA.c不能包含fileB.h(通过fileA.h),因为C编译器不知道extern“C”的含义,所以它抱怨它在字符串之前看到了一个标识符。不要尝试在fileA.c或fileA.h中包含fileB.h。它不需要
答案 4 :(得分:-1)
fileA.c还需要包含fileA.h我相信。