You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 02:00:28