本人在最近研究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”,表示不去链接为可执行程序,只需编译为.o文件
root@mack-VirtualBox:/home/mack/tmp_code# gcc -c test.c -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");
}