在c++中使用c库的问题

trouble using c library in c++

本文关键字:问题 c++      更新时间:2023-10-16

为了教自己一点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 s
extern "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