GCC Link Sequence Issue

GCC Link Sequence Issue

  1. GCC Link Background

GCC linker will link some object files to only one object file. During this time, it must replace all symbols(parameters/functions) to memory address(parameters address/functions address), for referring all sections in your object.

The most standard functions are located in “libc.a”(a means achieve), or located in shared dynamic lib “libc.so”(so means share object). these libs always located in /lib/ or /usr/lib/ or other folders of gcc finding setting.

  1. Simple Case
//test.c
#include <stdio.h>
int main(void)
{
    printf("Hello World!\n");
    return 0;
}

Use gcc test.c -o test to make a quick compile, for making *.c to *.exe or *.bin.

  1. four entire steps in Gcc Compile
gcc -E sqltest.c -o sqltest.i	//firstly, make *.c preprocessing to *.i
gcc -S sqltest.i -o sqltest.s	//secondly, make *.i compiling to *.s   
gcc -c sqltest.s -o sqltest.o	//thirdly, make *.s assemblying to *.o  
gcc sqltest.o 'mysql_configs --libs' -o sqltest 
//finally, make *.o and *.so/*.lib/*.dll linking to *.bin
//which 'mysql_configs --libs' equal to "-L/usr/lib/x86_64-linux-gnu -lmysqlclient -lpthread -lm -lrt -ldl"
  1. Sequence issue in linking

if you use gcc 'mysql_configs --libs'sqltest.o -o sqltest to make a link, you will get errors which said “undefined reference to xxx”. but why ?

because the finding sequence about symbols and libs of linking of GCC, is from Left to Right, according to -L sequence. So the Mysql API in sqltest.o can not find its references if you put the mysql libs to the left place of the sqltest.o.

Solutions:

Put the lowest layer libs to the end of the linking command, like gcc obj($?) -l (top logic libs) -l (middle packeted libs) -l (system libs) -o $@.

Or use repeat option to your linking command, make the “ld” keep finding refer libs in your command.

  1. Other Usage on library connection

use readelf -d sqltest or ldd sqltest to see the reference connection of a .bin/.so/.lib.

  1. Hope you have a strong makefile and happy compiling on your code.

End.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值