Makefile生成可执行文件失败:符号多重定义错误求助
链接阶段函数符号多重定义问题解决
编译程序时已成功生成所有.o目标文件,但链接阶段出现函数符号多重定义错误,无法生成可执行文件mmake。
提供的Makefile代码
CC = gcc CFLAGS = -g -std=gnu11 -Wall mmake: mmake.o parser.o $(CC) $(CFLAGS) -o mmake parser.o mmake.o parser.o: parser.c parser.h $(CC) $(CFLAGS) -c parser.c mmake.o: mmake.c $(CC) $(CFLAGS) -c mmake.c
编译错误输出
gcc -g -std=gnu11 -Wall -c mmake.c gcc -g -std=gnu11 -Wall -c parser.c gcc -g -std=gnu11 -Wall -o mmake parser.o mmake.o /usr/bin/ld: mmake.o: in function `parse_makefile': /home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:201: multiple definition of `parse_makefile'; parser.o:/home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:201: first defined here /usr/bin/ld: mmake.o: in function `makefile_del': /home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:301: multiple definition of `makefile_del'; parser.o:/home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:301: first defined here /usr/bin/ld: mmake.o: in function `makefile_default_target': /home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:226: multiple definition of `makefile_default_target'; parser.o:/home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:226: first defined here /usr/bin/ld: mmake.o: in function `makefile_rule': /home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:238: multiple definition of `makefile_rule'; parser.o:/home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:238: first defined here /usr/bin/ld: mmake.o: in function `rule_prereq': /home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:254: multiple definition of `rule_prereq'; parser.o:/home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:254: first defined here /usr/bin/ld: mmake.o: in function `rule_cmd': /home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:267: multiple definition of `rule_cmd'; parser.o:/home/c15/c15osn/workspace/Cprogg/SysN2022/Mmake/parser.c:267: first defined here collect2: error: ld returned 1 exit status make: *** [Makefile:9: mmake] Error 1
解决步骤
- 检查
mmake.c文件,若存在#include "parser.c"语句,将其修改为#include "parser.h"。C语言中直接包含源文件会导致该文件的函数代码被编译进多个目标文件,链接时触发多重定义错误,正确做法是通过头文件声明函数,源文件实现函数。 - 为
parser.h添加头文件保护,避免重复包含引发的潜在问题:#ifndef PARSER_H #define PARSER_H // parser.h中的函数声明、结构体定义等内容 #endif - 执行
make clean清理已生成的目标文件,再运行make重新编译链接。
内容的提问来源于stack exchange,提问作者Yohio
相关产品推荐
相关产品推荐

