本人在最近研究u-boot的代碼,鏈表操作時候寫了如下代碼:
#include <stdio.h>
typedef unsigned char u8;
struct tmp
{
u8* name;
u8* lenth;
u8* age;
};
struct tmp *tmp;
#define __aligned(x) __attribute__((aligned(x)))
#define ll_entry_declare(_type, _name, _list) \
_type _u_boot_list_2_##_list##_2_##_name __aligned(4) \
__attribute__((unused, \
section(".u_boot_list_2_"#_list"_2_"#_name)))
#define ll_entry_get(_type, _name, _list) \
({ \
extern _type _u_boot_list_2_##_list##_2_##_name; \
_type *_ll_result = \
&_u_boot_list_2_##_list##_2_##_name; \
_ll_result; \
})
#define U_BOOT_DRIVER(__name) \
ll_entry_declare(struct tmp, __name, tmp)
#define DM_GET_DRIVER(__name) \
ll_entry_get(struct tmp, __name, tmp)
U_BOOT_DRIVER(tmp1) = {
.name = "tmp1",
.lenth = "1",
.age = "11",
};
U_BOOT_DRIVER(tmp2) = {
.name = "tmp2",
.lenth = "2",
.age = "22",
};
U_BOOT_DRIVER(tmp3) = {
.name = "tmp3",
.lenth = "3",
.age = "33",
};
void test()
{
struct tmp *tmp_ls2 = DM_GET_DRIVER(tmp2);
printf("tmp_ls2's name is %s\n", tmp_ls2->name);
}
將他編譯爲靜態庫,但是報錯
root@mack-VirtualBox:/home/mack/tmp_code# gcc test.c -o test.o
/usr/lib/gcc/x86_64-linux-gnu/5/../../../x86_64-linux-gnu/crt1.o:在函數‘_start’中:
(.text+0x20):對‘main’未定義的引用
問題在於我代碼中沒有main函數,但是編譯器認爲我的程序爲可執行的程序,修改方法添加“-c”
root@mack-VirtualBox:/home/mack/tmp_code# gcc -c test.s -o test.o
root@mack-VirtualBox:/home/mack/tmp_code# ar rcs libtest.a test.o
root@mack-VirtualBox:/home/mack/tmp_code# ls
libtest.a test.c test.o
root@mack-VirtualBox:/home/mack/tmp_code# vim main.c
root@mack-VirtualBox:/home/mack/tmp_code# gcc main.c libtest.a
main.c: In function ‘main’:
main.c:6:2: warning: implicit declaration of function ‘test’ [-Wimplicit-function-declaration]
test();
^
root@mack-VirtualBox:/home/mack/tmp_code# ls
a.out libtest.a main.c test.c test.o
root@mack-VirtualBox:/home/mack/tmp_code# ./a.out
tmp_ls2's name is tmp2
test over!
因爲沒有進行聲明test報了一個警告,main文件的代碼如下:
#include <stdio.h>
#include <stdlib.h>
void main()
{
test();
printf("test over! \n");
}