undefined reference error in VScode
Solution 1
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
To fix this, simply add your test.c
file to the compilation by either doing gcc main.c test.c
.
Solution 2
If you are trying to include extra class files and this is your original run command:
cd "c:\myfolder\" ; if ($?) { g++ mainfile.cpp -o mainfile } ; if ($?) { .\mainfile}
add the extra file names (Shape.cpp & Circle.cpp for example) like this:
cd "c:\myfolder\" ; if ($?) { g++ mainfile.cpp Shape.cpp Circle.cpp -o mainfile } ; if ($?) { .\mainfile}
and run again
Related videos on Youtube
Ting-Wei Chien
Updated on August 25, 2021Comments
-
Ting-Wei Chien over 2 years
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
the error messages 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); }
headfile.h
extern int aa; extern float bb; void function(void);
-
Ra'Jiska almost 6 yearsCould you provide your compilation line ?
-