undefined reference error in VScode
Asked Answered
H

3

8

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);
Harbaugh answered 30/6, 2018 at 17:43 Comment(1)
Could you provide your compilation line ?Misfit
P
10

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 doing gcc main.c test.c.

Pot answered 30/6, 2018 at 17:55 Comment(0)
S
7

The answer provided by @Ra'Jiska is correct but doing it is not straightforward if you want to compile your code using VScode. You need to indicate to tasks.json (file generated by VScode with the commands to compile the code) which extra files your program needs to compile.

More specifically, you need to add the line "${fileDirname}/test.c" in the "args" section of the "tasks" list.

Spoon answered 28/5, 2022 at 20:47 Comment(1)
what if the file I need is a library with a .h and a .lib. What and where do I have to add to .json?Vinylidene
I
1

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

Inverson answered 10/10, 2020 at 19:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.