gcc 报错undefined reference to `main' collect2: error: ld returned 1 exit status

发布时间 2023-07-11 10:26:21作者: Marchyi

简单的错误,以备后察。

gcc 52_process_fork_wait.c 
/usr/bin/ld: /usr/lib/gcc/x86_64-linux-gnu/9/../../../x86_64-linux-gnu/Scrt1.o: in function `_start':
(.text+0x24): undefined reference to `main'
collect2: error: ld returned 1 exit status

已解决,因为vscode编辑后,未保存源文件而直接在terminal里gcc,特别是vscode编辑多个源文件,随手保存编辑区。

gcc

GCC(GNU Compiler Collection)的编译过程可以划分为四个阶段:

常用 gcc 选项

gcc [options] file...
-E :仅执行预处理(不要编译、汇编或链接)。
-S :只编译(不汇编或链接)。
-c :编译和汇编,但不链接。
-o <file> :指定输出文件。
-pie :创建一个动态链接、位置无关的可执行文件。
-I :指定头文件的包含路径。
-L :指定链接库的包含路径。
-shared :创建共享库/动态库。
-static :使用静态链接。
--help :显示帮助信息。

示例

默认生成 a.out

$ gcc 52_process_fork_wait.c 
$ ls
51_process_fork.c  52_process_fork_wait.c  a.out  ch02
$ ./a.out 
hello world (pid:1067) 
Hello, I am child (pid: 1068)
hello, I am parent of 1068  (wc:1068) (pid: 1067)

-o

$ gcc 51_process_fork.c -o 51_process_fork
$ ls
51_process_fork  51_process_fork.c  52_process_fork_wait.c  a.out  ch02
$ ./51_process_fork 
hello world (pid:1222) 
hello, I am parent of 1223 (pid: 1222)
Hello, I am child (pid: 1223)