在c++中使用c库的问题
trouble using c library in c++
为了教自己一点c++,我决定写一个小程序来给我的赛泰克X52 Pro操纵杆显示器写文字。
我想使用爱德华的c语言库http://plasma.hasenleithner.at/x52pro/
我知道如果我想在我的c++程序中使用它们,我必须在方法周围放置一个"外部C"。但这意味着更改库的头文件-然后它就不会再构建了。在这种情况下,正确的方法是什么?
编辑:建议的方法部分有效。
Comm.cpp:
...
extern "C"{
#include <x52pro.h>
}
using namespace std;
int main ( int argc, char *argv[] ) {
cout<<"entered main"<<endl;
char *String;
strcpy(String,"testing");
struct x52 *hdl = x52_init();
x52_settext(hdl, 0,String , 7);
x52_close(hdl);
return EXIT_SUCCESS;
}
错误信息:
Comm.o: In function `main':
Comm.cpp|38| undefined reference to `x52_init'
Comm.cpp|39| undefined reference to `x52_settext'
Comm.cpp|40| undefined reference to `x52_close'
这些方法都是在x52pro.h
要在C头文件中使用extern "C"
,请将其包装为
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
或者可以用extern "C"
#include
sextern "C" {
#include <chdr1.h>
#include <chdr2.h>
}
当链接你的应用程序时,你必须告诉链接器要使用什么库以及库在哪里。从您的链接中,您还必须添加libusb。它看起来大致像这样
g++ -o app_name Comm.o -L /path/to/library -lx52pro -lusb
当库安装在system lib目录下时,可以省略-L /path/...
部分。如果使用Makefile,可以在一些变量中定义它,通常是
LDFLAGS = -L /path/to/library
LDLIBS = -lx52pro -lusb
参见编译和链接和维基百科-链接器(计算)
在您的c++代码中,您可以像这样用extern "C"
包围包含的头文件:
extern "C" {
#include "c_header_file.h"
}
那么,您就不需要修改第三方库的头文件。
#ifdef __cplusplus
extern C {
#endif
...
#ifdef __cplusplus
}
#endif
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题