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

使用GCC编译时出现“undefined reference to ...”错误的原因排查求助

GCC编译时出现“undefined reference to ...”错误的原因排查求助

大家好,我最近在编译一个较大的项目时遇到了链接错误,之前用Code Blocks IDE编译完全没问题。为了定位问题,我搭了一个最小复现项目,结果还是触发了同样的错误,想请大家帮忙看看问题出在哪。

我的项目结构对应的代码如下:

Makefile

build:
	gcc -std=c99 ./src/*.c -o helloWorld
run:
	./helloWorld
clean:
	rm helloWorld

src/main.c

#include <stdio.h>
#include "type.h"

int main() {
    defineNum();
    printf("%d", num);
    return 0;
}

src/type.h

#ifndef TYPE_H
#define TYPE_H

extern int num;
void defineNum(void);

#endif

src/type.c

#include "type.h"

int a = 1;
void defineNum(void) {
    num = a;
}

执行make build后,得到的错误信息如下:

gcc -std=c99 ./src/*.c -o helloWorld
C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\...\AppData\Local\Temp\ccI5FfcG.o:main.c:(.rdata$.refptr.num[.refptr.num]+0x0): undefined reference to `num'
collect2.exe: error: ld returned 1 exit status
make: *** [Makefile:2: build] Error 1

我查过相关资料,明白变量声明和定义的区别:num在type.h里用extern做了声明,但我在type.c的defineNum函数里直接对num进行了赋值操作。表面上看,问题好像出在函数内定义变量或者跨文件的变量使用上,但这似乎不太符合我对C语言的认知。

我现在猜测问题可能和编译链接的流程有关,而不是C语言语法本身的问题,但我对编译过程的了解比较有限,想请教各位:这个错误的根源到底是什么?应该怎么修复呢?

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 07:04:32