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

C语言gcc编译时报undefined reference to function错误如何解决

问题根因
  • 你在funcs.c中定义的plus和minus函数使用了inline修饰,GCC默认规则下,无static修饰的inline函数不会生成对外可见的函数符号,仅作为内联优化使用,链接器找不到对应的函数实现就会报未定义引用错误。
  • main.c中错误引入了#include "funcs.c",C语言正确的用法是引入对应的头文件而非源文件,你同时编译funcs.c和main.c时还会导致符号重复定义的后续问题。
  • help.h中声明的extern int a/b/z/wh完全无效,这些变量都是对应函数内部的局部变量,作用域仅在函数内部,外部无法访问,不需要加extern声明。
修复步骤
  1. 修改funcs.c中的函数定义,直接删掉inline修饰即可(初学者如果没有明确的内联需求,不需要加inline):
// funcs.c 修改后示例
#include <stdio.h>

void plus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a + b;
    printf("The result is: %d\n", a);
}

void minus(void)
{
    int a = 0;
    int b = 0;
    printf("Pls insert a numb\n");
    scanf("%d", &a);
    printf("Pls insert a numb\n");
    scanf("%d", &b);
    a = a - b;
    printf("The result is: %d\n", a);
}
  1. 修改main.c,把#include "funcs.c"替换为引入头文件#include "help.h",可额外补充退出逻辑避免死循环:
// main.c 修改后示例
#include <stdio.h>
#include "help.h"

int main()
{
    int z = 0;
    int wh = 1;
    while (wh == 1)
    {
        printf("What you want?\n1-Plus\n2-Minus\n3-Exit\n");
        scanf("%d", &z);
        if (z == 1)
        {
            plus();
        }
        else if (z == 2)
        {
            minus();
        }
        else if (z == 3)
        {
            wh = 0;
        }
    }
    printf("The program ended\n");

    return 0;
}
  1. 修改help.h,删掉无用的extern变量声明,同时把函数声明前的inline去掉:
// help.h 修改后示例
void minus(void);
void plus(void);
  1. 用原来的编译命令重新编译即可正常运行:
    gcc funcs.c main.c -o test
    运行生成的test程序即可。

内容的提问来源于stack exchange,提问作者ops400

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:57:03