Tin*_*ien 8 c undefined-reference visual-studio-code
我正在测试如何在 C 中使用 extern ,因此我为 main.c、test.c、headfile.h 创建三个文件。我想在 headfile.h 中声明变量和函数,在 test.c 中定义,然后在 main.c 中打印出变量并调用函数。它通过使用 Dev c++ 成功运行,但是,当我将完全相同的文件放入VScode 显示错误,指出存在未定义的变量引用
错误消息 在此处输入图像描述
#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;
}
Run Code Online (Sandbox Code Playgroud)
#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);
}
Run Code Online (Sandbox Code Playgroud)
extern int aa;
extern float bb;
void function(void);
Run Code Online (Sandbox Code Playgroud)
Ra'*_*ska 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
Run Code Online (Sandbox Code Playgroud)
要解决此问题,只需test.c
通过执行以下操作将文件添加到编译中gcc main.c test.c
。
小智 7
@Ra'Jiska 提供的答案是正确的,但如果您想使用 VScode 编译代码,那么这样做并不简单。您需要指示tasks.json
(VScode 使用编译代码的命令生成的文件)您的程序需要编译哪些额外文件。
"${fileDirname}/test.c"
更具体地说,您需要在“任务”列表的“args”部分添加该行。
归档时间: |
|
查看次数: |
51842 次 |
最近记录: |