c++ - 我可以在 C++ 项目中混合使用 c 和 cpp 文件吗?

标签 c++ c linker

我有一个项目,其中混合了 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/

相关文章:

c++ - 尝试 [[nodiscard]] 没有成功

c++ - 调试后 CMD 窗口什么也没有显示

C++ Win32 : Attach a child window to main window

c - Win32::API 给出错误的原型(prototype)错误

c - 我可以从一个位置更改结构成员,但不能从另一个位置更改结构成员

c++ - QVideoFrame 的许多构造函数中的 1 个的未定义引用

c++ - 指针:在 C++ 中不可赋值的表达式

c - 归零并初始化 C 结构

c - 链接期间对全局变量的 undefined reference

库中的.text、.data、.bss .a 文件可以分成单独的部分吗