Ting-Wei Chien
Ting-Wei Chien

Reputation: 169

undefined reference error in 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

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);

Upvotes: 9

Views: 57915

Answers (3)

Ra&#39;Jiska
Ra&#39;Jiska

Reputation: 1049

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.

Upvotes: 10

Alexandre Henrique
Alexandre Henrique

Reputation: 91

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.

Upvotes: 9

SilverTech
SilverTech

Reputation: 429

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

Upvotes: 1

Related Questions