簡體   English   中英

gcc如何鏈接靜態庫?

[英]How does gcc link static library?

我有一個簡單的程序,使用靜態庫控制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"
}

您可能沒有使用extern "C"

如果我將cpp文件重命名為c文件編譯成功。 問題是什么?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM