这是我的两个源代码文件
//main.c
#include "stdio.h"
int sum(int *a, int n);
int array[2] = {1, 2};
int main()
{
int val = sum(array,2);
printf("%d\n", val);
return 0;
}
//sum.c
int sum(int *a, int n)
{
int i=0,s =0;
for(;i<n;i++)
s+=a[i];
return s;
}
通过以下步骤生成可执行文件:
# preprocessing
gcc -E main.c -o main.i
gcc -E sum.c -o sum.i
# compilation
gcc -Og -S main.i -o main.s
gcc -Og -S sum.i -o sum.s
# assembling
as main.s -o main.o
as sum.s -o sum.o
# linking
ld -o prog sum.o main.o -lc --entry main
但是生成的可执行文件运行不了:
$ ./prog
-bash: ./prog: No such file or directory
$ file ./prog
prog: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib/ld6, not stripped
$ stat prog
File: prog
Size: 6424 Blocks: 16 IO Block: 4096 regular file
Device: 801h/2049d Inode: 3153139 Links: 1
Access: (0777/-rwxrwxrwx) Uid: ( 1000/ u) Gid: ( 1000/ u)
Access: 2021-01-22 17:41:02.516854257 +0800
Modify: 2021-01-22 17:31:02.969230783 +0800
Change: 2021-01-22 17:40:57.432364965 +0800
Birth: -
我使用的操作系统是 ubuntu 18.04 x86-64
1
azenk 2021-01-22 18:20:42 +08:00
readelf -s
|
2
movq OP @azenk
Symbol table '.symtab' contains 13 entries: Num: Value Size Type Bind Vis Ndx Name 0: 0000000000000000 0 NOTYPE LOCAL DEFAULT UND 1: 00000000004000e8 0 SECTION LOCAL DEFAULT 1 2: 0000000000400150 0 SECTION LOCAL DEFAULT 2 3: 0000000000601000 0 SECTION LOCAL DEFAULT 3 4: 0000000000000000 0 SECTION LOCAL DEFAULT 4 5: 0000000000000000 0 FILE LOCAL DEFAULT ABS main.c 6: 0000000000000000 0 FILE LOCAL DEFAULT ABS sum.c 7: 0000000000400109 69 FUNC GLOBAL DEFAULT 1 sum 8: 0000000000601008 0 NOTYPE GLOBAL DEFAULT 3 __bss_start 9: 00000000004000e8 33 FUNC GLOBAL DEFAULT 1 main 10: 0000000000601000 8 OBJECT GLOBAL DEFAULT 3 array 11: 0000000000601008 0 NOTYPE GLOBAL DEFAULT 3 _edata 12: 0000000000601008 0 NOTYPE GLOBAL DEFAULT 3 _end |
3
katsusan 2021-01-22 18:47:44 +08:00
strace -t ./prog
|
4
hello2060 2021-01-22 18:59:19 +08:00
[21:54:50] ~ $ man ld
[21:56:50] ~ $ ld -o prog sum.o main.o -lc -e main Undefined symbols for architecture x86_64: "main", referenced from: implicit entry/start for main executable (maybe you meant: _main) ld: symbol(s) not found for architecture x86_64 [21:57:20] ~ $ ld -o prog sum.o main.o -lc -e _mai [21:57:34] ~ $ ./prog 3 我在 mac 上的结果, |
5
XiaoxiaoPu 2021-01-22 19:09:41 +08:00
|
6
movq OP `ldd prog`
查看到` /lib/ld64.so.1 => /lib64/ld-linux-x86-64.so.2.` `/lib/ld64.so.1` 不存在 所以在 ld 链接时添加`--dynamic-linker=/lib64/ld-linux-x86-64.so.2`这个选项,链接出来的 prog 可以执行 但是执行结果是 ``` 3 Segmentation fault (core dumped) ``` 有点好奇为什么会出现`Segmentation fault (core dumped)` |
7
movq OP 解决了,gcc 调用 ld 的时候会自动传入很多参数,可以通过 gcc -v 来查看到底传了什么参数
把这些参数复制然后手动传给 ld,就正常了 |