I have two C files in the same folder:
file1.c
#include <stdio.h>
int a;
int main()
{
a = 1;
printf("%d",a);
return 0;
}
file2.c
#include <stdio.h>
extern int a;
int main()
{
a = 1;
printf("%d",a);
return 0;
}
I run file2.c on vscode and its return:
C:/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/12.1.0/../../../../x86_64-w64-mingw32/bin/ld.exe:C:UsersDuongAppDataLocalTempcc8Tiaj4.o:file2.c:(.rdata$.refptr.a[.refptr.a]+0x0): undefined reference to `a'
collect2.exe: error: ld returned 1 exit status
I have try many way sincluding add header file, but it doesn’t work at all.
Can someone tell me if my code or my compiler has any problem
2
Answers
main
function defined in both files it proves that you do not link them together.file1.c
file2.c
Then compile and link them from command line
Visual studio code is not for a very beginners as it requires some configuration and understanding how thing work.
Install Eclipse CDT which manages the projects for you without problems
No, your compiler is telling you the truth. In
pru2.c
you have amain()
routine (as inpru1.c
) so I must assume both are different programs.You have defined a variable in
pru2.c
that will be found in another compilation unit (module) of the same program (a process cannot access the memory of another, so you can acces no variables of another, different program) For that variable to be viewable, both,file1.c
andfile2.c
need to be compiled together (or better said, linked together) into a single problem. But that cannot be done, because you have onemain()
function on each, and when trying to link both compilation units together, you will get a linker error telling you that you have two definitions formain
in the same program (which cannot be)Just change the name of
main()
routine in one of the files to something different (you will not use it) and compile both modules together into the same programAs the
main()
functions in both files are the same, just deletemain()
infile1.c
makint it to appear as:while
file2.c
remains the same:and then you can compile them separately:
or all together: