我有一个项目,其中混合了 c 文件和 cpp 文件。链接器向我抛出错误:
undefined reference to <all my functions in the c files>
在我将所有 *.c
文件重命名为 *.cpp
之后,错误消失了。那么我不能混合这些文件吗?或者这是一些编译器/链接器选项问题?
我的选择:
GCC C++ 编译器:
-I/usr/include/glib-2.0 -I/usr/include/gtk-2.0 -I"/myPath" -O0 -g3 \
-Wall -c -fmessage-length=0 `pkg-config --cflags glib-2.0 gtk+-2.0
GCC C 编译器:
-I/usr/include/glib-2.0 -I/usr/include/gtk-2.0 -I"/myPath" -O0 -g3 \
-Wall -c -fmessage-length=0 -std=c99 `pkg-config --cflags glib-2.0 gtk+-2.0`
GCC C++ 链接器:
-L/usr/include/glib-2.0/glib `pkg-config --libs gtk+-2.0`
既然它说 C++ 链接器,这是否意味着来自 c 文件的目标文件不能链接到项目中(默认情况下)?
最佳答案
您需要像这样包装 C 代码
extern "C" {
#include "sample1.h"
}
更好的方法是像 this StackOverflow question 中那样, 在 C 头文件中。
使用:
#ifdef __cplusplus
extern "C" {
#endif
在所有 C 头文件的开头。
并使用:
#ifdef __cplusplus
}
#endif
在所有 C 头文件的末尾。
关于c++ - 我可以在 C++ 项目中混合使用 c 和 cpp 文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20118673/