c++ - gcc如何链接静态库?

标签 c++ gcc

我有一个简单的程序使用静态库来控制 pci 设备。我有一些例子。但我想给自己举一些例子,但我无法链接静态库。

我有 3 个文件:led.cpp main.cpp main.h

gcc -c led.cpp -I../utils -I../driver -o led.o

gcc -c main.cpp -I../utils -I../driver -o main.o

没关系。成功创建 main.o 和 led.o 目标文件。

但是当链接状态时,它坏了。 24dsi20c500k_utils.a 和 24dsi20c500k_dsl.a 静态库。

gcc led.o main.o ../utils/24dsi20c500k_utils.a ../docsrc/24dsi20c500k_dsl.a -o led

显示输出:

led.o: In function `led_tests(int)':
led.cpp:(.text+0x18): undefined reference to `gsc_label(char const*)'
led.cpp:(.text+0x31): undefined reference to `dsi20c500k_initialize(int, int)'
led.cpp:(.text+0x39): undefined reference to `gsc_label_level_inc()'
led.cpp:(.text+0x5b): undefined reference to `dsi20c500k_led(int, int, int, int*)'
led.cpp:(.text+0x81): undefined reference to `dsi20c500k_led(int, int, int, int*)'
led.cpp:(.text+0xa2): undefined reference to `gsc_label_level_dec()'
led.cpp:(.text+0xb1): undefined reference to `dsi20c500k_initialize(int, int)'
main.o: In function `_perform_tests(int)':
main.cpp:(.text+0x3a1): undefined reference to `gsc_label(char const*)'
main.cpp:(.text+0x3c6): undefined reference to `gsc_id_driver(int, char const*)'
main.o: In function `main':
main.cpp:(.text+0x42c): undefined reference to `gsc_label_init(int)'
main.cpp:(.text+0x49a): undefined reference to `gsc_id_host()'
main.cpp:(.text+0x4a4): undefined reference to `gsc_count_boards(char const*)'
main.cpp:(.text+0x4b6): undefined reference to `gsc_select_1_board(int, int*)'
main.cpp:(.text+0x4d7): undefined reference to `gsc_label(char const*)'
main.cpp:(.text+0x500): undefined reference to `gsc_dev_open(unsigned int, char const*)'
main.cpp:(.text+0x54f): undefined reference to `gsc_dev_close(unsigned int, int)'
collect2: ld returned 1 exit status
make: *** [led] Error 1

如果我将 cpp 文件重命名为 c 文件编译成功。有什么问题?

最佳答案

gcc -c main.cpp 会将您的代码编译为 C++ 代码。

然后可能发生的情况是,您的 main.cpp 包含其他头文件,这些头文件旨在编译为 C++。这意味着当在 C++ 程序中包含这些头文件时,gcc 将假定头文件声明的所有内容都是 C++。

如果不是,如果您尝试链接到编译器假定为 C++ 的 C 代码,则会出现链接器错误。

您可以通过声明这些头文件是 C 来解决这个问题。例如在你的 main.cpp 中你会做

extern "C" {
#include "some_c_lib.h"
}

关于c++ - gcc如何链接静态库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13481728/

相关文章:

c++ - g++ 的严格别名警告准确性

c++ - 模板实例化问题

C++11 is_pod 与 GCC 4.6

linux - GCC 选项的 -shared 和 -Wl,-shared 的区别

c# - CLI/C# 将 std::vector<> 结构数据传递给 C#

c++ - GCC 会为运行时保留固定值的算术运算还是编译输出?

python - 依赖于 gcc 的 pyzmq 安装错误

c++ - 如何将 "ENTER"case 实现到 switch 语句中

c++ - 有关代码维护的建议

c++ - 使用适用于 Win32 的英特尔 C++ 编译器编译 Qt 时出错,我做错了什么?