I'm still a beginner and I'm working with eclipse.
我仍然是一个初学者,我正在使用eclipse。
I have a project that had c files and cpp files mixed in it. The linker throws errors at me:
我有一个项目,其中包含c文件和cpp文件。链接者向我抛出错误:
undefined reference to <all my functions in the c files>
After I rename all *.c
files to *.cpp
the errors vanish. So can't I mix those files or is this some compiler/linker options problem?
在我重命名所有*之后。c文件*。cpp消失的错误。我不能把这些文件混在一起,或者这是编译器/链接器选项的问题?
My options:
我的选择:
GCC C++ Compiler:
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 Compiler:
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++ Linker:
GCC c++链接:
-L/usr/include/glib-2.0/glib `pkg-config --libs gtk+-2.0`
OK, since it says C++ Linker, does that mean object files from c files cannot be linked into the project (by default)?
好的,既然它说的是c++链接器,这是否意味着来自C文件的对象文件不能链接到项目中(默认情况下)?
2 个解决方案
#1
4
extern "C"
is one approach. The other approach, assuming your C files are of the (almost ubiquitous) sort which are already compilable as C++, is simply to coerce the compiler into treating them as C++ (which gives them the appropriate name mangling to work with your C++ files). For GCC, this is -x c++
.
走读是一种方法。另一种方法,假设您的C文件属于(几乎无处不在的)类型,并且已经可以编译为c++,那么只需强制编译器将它们视为c++(这给了它们适当的名称管理,以处理您的c++文件)。对于GCC,这是-x c++。
#2
12
You need to wrap the C code like so
您需要像这样封装C代码
extern "C" {
#include "sample1.h"
}
A better way to do it is like in this * question, in the C header files.
更好的方法是在这个*问题中,在C头文件中。
use:
使用:
#ifdef __cplusplus
extern "C" {
#endif
At the start of all C header files.
在所有C头文件的开头。
and use:
和使用:
#ifdef __cplusplus
}
#endif
At the end of all C header files.
在所有C头文件的末尾。
#1
4
extern "C"
is one approach. The other approach, assuming your C files are of the (almost ubiquitous) sort which are already compilable as C++, is simply to coerce the compiler into treating them as C++ (which gives them the appropriate name mangling to work with your C++ files). For GCC, this is -x c++
.
走读是一种方法。另一种方法,假设您的C文件属于(几乎无处不在的)类型,并且已经可以编译为c++,那么只需强制编译器将它们视为c++(这给了它们适当的名称管理,以处理您的c++文件)。对于GCC,这是-x c++。
#2
12
You need to wrap the C code like so
您需要像这样封装C代码
extern "C" {
#include "sample1.h"
}
A better way to do it is like in this * question, in the C header files.
更好的方法是在这个*问题中,在C头文件中。
use:
使用:
#ifdef __cplusplus
extern "C" {
#endif
At the start of all C header files.
在所有C头文件的开头。
and use:
和使用:
#ifdef __cplusplus
}
#endif
At the end of all C header files.
在所有C头文件的末尾。