VScode 中未定义的引用错误 [英] undefined reference error in VScode
问题描述
我正在测试如何在 C 中使用 extern,所以我为 main.c、test.c、headfile.h 创建了三个文件.我想在headfile.h中声明变量和函数,在test.c中定义,然后在main.c中打印出变量和调用函数它通过使用 Dev c++ 成功运行,但是,当我将完全相同的文件放入 VScode 时,它显示错误,即存在对变量的未定义引用
I'm testing the how to use extern in C ,so I create three files for main.c, test.c, headfile.h . I want to declare variable and function in headfile.h,define in the test.c ,then print out the variable and call function at the main.c It works successfully by using Dev c++,however, when I put the exact same files into VScode it show errors that there are undefined reference to variables
错误信息在此处输入图片描述
#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);
}
headfile.h
extern int aa;
extern float bb;
void function(void);
推荐答案
您的 main.c
文件似乎没有与 test.c
链接.我已经能够使用以下编译命令重现完全相同的错误消息:
It looks like your main.c
file is not being linked with test.c
.
I have been able to reproduce the exact same error message using the following compilation commands:
$ 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
文件添加到编译中即可.
To fix this, simply add your test.c
file to the compilation by either doing gcc main.c test.c
.
这篇关于VScode 中未定义的引用错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!