VSCode中使用gcc编译模块化C代码时出现undefined reference错误的问题及解决
Problem Description
I was working on modular C code in VSCode and ran into a linker error when compiling with GCC. Here's my code structure:
hauptteil.c (Main File)
#include "nebenfkt.h" #include <stdio.h> #include <stdlib.h> int main (void) { int x =10; int ergebnis=0; ergebnis =ver(x); printf("Doubled number: %d", ergebnis); return 0; }
nebenfkt.h (Header File)
int ver(int x);
nebenfkt.c (Implementation File)
#include "nebenfkt.h" #include <stdio.h> #include <stdlib.h> int ver(int x) { int rueck; rueck= x*2; return rueck; }
When I executed this compile command:
gcc hauptteil.c -o function
VSCode returned this error message:
undefined reference to `ver' collect2.exe: error: ld returned 1 exit status
Root Cause
The error occurs because I only compiled the main source file (hauptteil.c) and didn't include the implementation file (nebenfkt.c). The header file just declares the ver function so the compiler knows its signature, but the linker needs the actual compiled object code from nebenfkt.c to resolve the reference to ver in the main file.
Solution
To fix this undefined reference issue, you need to include all relevant source files in your GCC compile command. The correct command is:
gcc hauptteil.c nebenfkt.c -o function
This tells GCC to compile both hauptteil.c and nebenfkt.c into object files, then link them together to generate the final executable function.
内容的提问来源于stack exchange,提问作者vukstudent

