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

TEST语言词法分析程序编译报错求助:Undefined reference问题

编译错误解决:Undefined reference to 'fin'/'fout'

错误原因

你代码里的extern FILE *fin,*fout;是外部变量声明,它告诉编译器“这两个变量在其他文件或当前文件的其他位置定义”,但你的代码里根本没定义这两个变量,所以链接器找不到它们的实体,就报了Undefined reference错误。

两种解决办法

方法一:直接在main函数内定义变量(最直接)

把代码里的extern FILE *fin,*fout;改成FILE *fin,*fout;,这样就在main函数里完成了变量定义,链接器能找到变量实体。修改后的完整代码如下:

#include <stdio.h>
#include <string.h>

int main()
{

    char Scanin[300],Scanout[300];
    FILE *fin,*fout; // 去掉extern,直接定义

    printf("Please enter the source program file name (including the path): ");
    scanf("%s",Scanin);
    printf("Please enter the lexical analysis output file name (including the path):");
    scanf("%s",Scanout);
    if((fin=fopen(Scanin,"r"))==NULL)
             //Judge whether the input file name is correct
    {
        printf("\nError opening lexical analysis input file!\n");
        return 1;
                //Error in input file returned error code 1
    }

    if((fout=fopen(Scanout,"w"))==NULL)
        //Judge whether the output file name is correct
    {
        printf("\nError creating lexical analysis output file!\n");
        return 2;
                //Error in output file returned error code 2
    }
}

方法二:定义全局变量(适合后续扩展需要在其他函数使用的场景)

如果后续词法分析的其他函数要用到fin和fout,可以把变量定义在main函数外面,作为全局变量:

#include <stdio.h>
#include <string.h>

FILE *fin,*fout; // 全局定义变量

int main()
{

    char Scanin[300],Scanout[300];
    // 这里不需要extern,直接使用全局变量

    printf("Please enter the source program file name (including the path): ");
    scanf("%s",Scanin);
    printf("Please enter the lexical analysis output file name (including the path):");
    scanf("%s",Scanout);
    if((fin=fopen(Scanin,"r"))==NULL)
             //Judge whether the input file name is correct
    {
        printf("\nError opening lexical analysis input file!\n");
        return 1;
                //Error in input file returned error code 1
    }

    if((fout=fopen(Scanout,"w"))==NULL)
        //Judge whether the output file name is correct
    {
        printf("\nError creating lexical analysis output file!\n");
        return 2;
                //Error in output file returned error code 2
    }
}

编译验证

修改后,用C编译器(比如gcc)执行命令:

gcc your_code.c -o lexical_analyzer.exe

就能成功生成可执行文件了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:20:42