如何修复嵌入式C代码编译时的未定义引用链接错误?
MinGW64编译嵌入式C代码的链接错误及函数返回问题修复
问题场景
使用VSCode开发嵌入式C代码,通过MinGW64编译时出现两类问题:
- 执行编译命令
gcc .\main.c -o main.exe时触发链接错误,提示test_init、test_getCount、test_updateCount未定义 test.c中的test_init函数未返回分配的指针,存在未定义行为
代码结构:
- 根目录:
main.c ./test目录:test.h、test.c
完整代码
main.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "test/test.h" int main() { Test_t *deneme = test_init(5); int a = test_getCount(deneme); printf("one %d", a); test_updateCount(deneme, 10); int b = test_getCount(deneme); printf("two %d", b); return 0; }
test.h
#include <stdio.h> #include <stdint.h> #include <stdlib.h> typedef struct { int count; } Test_t; Test_t *test_init(int number); void test_updateCount(Test_t *tester, int number); int test_getCount(Test_t *tester);
test.c
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #include "test.h" Test_t *test_init(int number) { Test_t *deneme = malloc(sizeof(Test_t)); deneme->count = number; } void test_updateCount(Test_t *tester, int number) { tester->count = number; } int test_getCount(Test_t *tester) { return tester->count; }
链接错误信息
C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user\AppData\Local\Temp\ccSxcYgu.o:main.c:(.text+0x13): undefined reference to `test_init' C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user\AppData\Local\Temp\ccSxcYgu.o:main.c:(.text+0x23): undefined reference to `test_getCount' C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user\AppData\Local\Temp\ccSxcYgu.o:main.c:(.text+0x4b): undefined reference to `test_updateCount' C:/ProgramData/chocolatey/lib/mingw/tools/install/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.2.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:\Users\user\AppData\Local\Temp\ccSxcYgu.o:main.c:(.text+0x57): undefined reference to `test_getCount' collect2.exe: error: ld returned 1 exit status
问题修复
1. 链接错误修复
原因:编译命令仅处理了main.c,未将实现函数的test.c纳入编译流程,链接器无法找到函数的二进制实现。
解决方法:
- 直接一次性编译所有源文件:
gcc .\main.c .\test\test.c -o main.exe - 分步编译(适合大型项目):
- 先将
test.c编译为目标文件:gcc -c .\test\test.c -o test.o - 再编译
main.c并链接目标文件:gcc .\main.c test.o -o main.exe
- 先将
2. test_init函数返回问题修复
原因:test_init函数声明返回Test_t*类型指针,但函数体中未返回分配的内存指针,属于未定义行为,可能导致程序崩溃或不可预期的结果。
修复后的test_init函数:
Test_t *test_init(int number) { Test_t *deneme = malloc(sizeof(Test_t)); // 建议添加内存分配失败的判断 if (deneme == NULL) { fprintf(stderr, "Memory allocation failed!\n"); return NULL; } deneme->count = number; return deneme; // 添加返回语句 }
内容的提问来源于stack exchange,提问作者Erdem Ün
相关产品推荐
相关产品推荐

