【问题标题】:undefined reference error in VScodeVScode中未定义的引用错误
【发布时间】:2018-12-09 13:28:27
【问题描述】:

我正在测试如何在 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;
}

test.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


【解决方案1】:

您的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

要解决此问题,只需通过执行 gcc main.c test.c 将您的 test.c 文件添加到编译中。

【讨论】:

    【解决方案2】:

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

    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}

    然后再次运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多