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

VSCode中使用gcc编译模块化C代码时出现undefined reference错误的问题及解决

Undefined Reference Error When Compiling Modular C Code with GCC in VSCode

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 18:42:44