Home > Net >  Visual Studio Code can't find reference to function
Visual Studio Code can't find reference to function

Time:01-05

I'm trying to use Visual Studio for a specific project but I can't get files to link properly. When including a header file with a defined function in another cpp file im getting an error undefined reference to testFunc() collect2.exe: error: ld returned 1 exit status

Thing is, this exact same code works perfectly in Eclipse. Can someone tell me what I'm doing wrong?

Test.cpp

#include "Other.h"

int main(){
   
    testFunc();
    return 0;
}

Other.h

#pragma once

void testFunc();

Other.cpp

#include "Other.h"
#include <iostream>
using namespace std;

void testFunc(){
    cout << "HelloWorld";
}

When Buildung, this occours:

Starting build...
C:\MinGW\bin\g  .exe -fdiagnostics-color=always -g C:\Users\johan\cu-workspace\TEst\Test.cpp -o C:\Users\johan\cu-workspace\TEst\Test.exe
C:\Users\johan\AppData\Local\Temp\cck3aAZo.o: In function `main':
C:/Users/johan/cu-workspace/TEst/Test.cpp:5: undefined reference to `testFunc()'
collect2.exe: error: ld returned 1 exit status

Build finished with error(s).

CodePudding user response:

If you build Other.h and Other.cpp as a project, then you need to configure the linker to add Other.lib into test project.
For a simple scenario, you can have all 3 files in one project and they should build just fine.

CodePudding user response:

According to your build info:

C:\MinGW\bin\g  .exe -fdiagnostics-color=always -g C:\Users\johan\cu-workspace\TEst\Test.cpp -o C:\Users\johan\cu-workspace\TEst\Test.exe

You can see that Other.cpp is not in your project, so you might need to add it into your project.

Since you are using VS code, you can write a simple command in terminal to build your code:

C:\MinGW\bin\g  .exe -g C:\Users\johan\cu-workspace\TEst\Test.cpp C:\Users\johan\cu-workspace\TEst\Other.cpp -o C:\Users\johan\cu-workspace\TEst\Test.exe
  • Related