VScode 中未定义的引用错误

问题描述 投票:0回答:3

我正在测试如何在 C 中使用 extern ,因此我为 main.c、test.c、headfile.h 创建了三个文件。我想在headfile.h中声明变量和函数,在test.c中定义,然后打印出变量并在main.c中调用函数 它通过使用 Dev c++ 成功运行,但是,当我将完全相同的文件放入 VScode 时,它显示错误,存在对变量的未定义引用

错误信息 enter image description here

main.c

#include <stdio.h>
#include <stdlib.h>
#include"D:\My Documents\Desktop\CODE\c\VScode\externTest\headfile.h"
int gVar = 1;

int main(void)
{
    extern float a;

    printf("a = %f\n",a);
    printf("gVar = %d\n",gVar);
    printf("aa = %d\n",aa);
    printf("bb = %f\n",bb);
    function ();
    system("pause");
    return 0;
}

测试.c

#include <stdio.h>
#include "D:\My Documents\Desktop\CODE\c\VScode\externTest\headfile.h" 
float a = 100;
int aa = 200;
float bb = 300;

void function (void){
    printf("yeh you got it!!\n");
    extern int gVar;
    gVar++;
    printf("gVar in test.c function = %d",gVar);
}

头文件.h

extern int aa;
extern float bb;
void function(void);
c visual-studio-code undefined-reference
3个回答
10
投票

您的

main.c
文件似乎未与
test.c
链接。 我已经能够使用以下编译命令重现完全相同的错误消息:

$ gcc main.c
/tmp/ccVqEXL5.o: In function `main':
main.c:(.text+0x8): undefined reference to `a'
main.c:(.text+0x38): undefined reference to `aa'
main.c:(.text+0x51): undefined reference to `bb'
main.c:(.text+0x69): undefined reference to `function'
collect2: error: ld returned 1 exit status

要解决此问题,只需执行

test.c
将您的
gcc main.c test.c
文件添加到编译中即可。


7
投票

@Ra'Jiska 提供的答案是正确的,但如果您想使用 VScode 编译代码,那么这样做并不简单。您需要向

tasks.json
(由 VScode 使用编译代码的命令生成的文件)指示您的程序需要编译哪些额外文件。

更具体地说,您需要在“任务”列表的“args”部分添加行

"${fileDirname}/test.c"


1
投票

如果您尝试包含额外的类文件,并且这是您原来的运行命令:

cd "c:\myfolder\" ; if ($?) { g++ mainfile.cpp -o mainfile } ; if ($?) { .\mainfile}

添加额外的文件名(例如 Shape.cpp 和 Circle.cpp),如下所示:

cd "c:\myfolder\" ; if ($?) { g++ mainfile.cpp Shape.cpp Circle.cpp -o mainfile } ; if ($?) { .\mainfile}

然后再次运行

© www.soinside.com 2019 - 2024. All rights reserved.