我有一个由其他人编写的 C 库,我希望从我的 C++ 程序中调用它。 C 头文件的结构如下:
#ifndef INC_MOVE_CLIENT_H
#define INC_MOVE_CLIENT_H
#ifdef __cplusplus
extern "C" {
#endif
...
int serverConnect(const char *, const char *, MoveStateDeferred *);
...
#ifdef __cplusplus
}
#endif
#endif // ... INC_MOVE_CLIENT_H
我像这样在我的 C++ 程序中调用 serverConnect:
#include "helloworld.h"
#include "moveclient.h"
int main(int argc, const char* argv[]) {
const char* ip = "192.168.1.2";
const char* port = "7899";
MoveStateDeferred* m;
serverConnect(ip, port, m);
}
根据 these instructions 这对我来说似乎是正确的但是当我尝试编译时,我得到:
$ gcc helloworld.cpp -o helloworld.out
/tmp/ccuS93Yu.o: In function `main':
helloworld.cpp:(.text+0x3c): undefined reference to `serverConnect'
collect2: ld returned 1 exit status
moveclient.c 具有 serverConnect 的实现,并且与其他文件位于同一目录中。我是否使用了不正确的命令进行编译?我需要做些什么才能同时编译 moveclient.c 吗?还是与编译命令无关的其他内容?
最佳答案
这不是编译问题,而是链接问题。
假设 moveclient.c
是您唯一需要的附加文件,那么您有多种选择:
您可以将.c 文件添加到编译行:
g++ helloworld.cpp moveclient.c -o helloworld.out
或者您可以将 .c(和您的 .cpp)文件编译为目标文件并链接它们
g++ -c helloworld.cpp
gcc -c moveclient.c
g++ helloworld.o moveclient.o -o helloworld.out
或者您可以将 moveclient 内容链接到一个库中,然后将该库添加到链接中。
创建库的详细信息将取决于您的系统以及您想要共享库还是动态库。但是,一旦您拥有了库,您的构建行将如下所示(假设您的库名为 libmoveclient.so
或 libmoveclient.a
)
g++ helloworld.cpp -L. -lmoveclient
或者如果您使用的是单独编译:
g++ -c helloworld.cpp
g++ helloworld.o -L. -lmoveclient
关于c++ - 从 C++ 调用 C 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11753174/