skip to Main Content

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:MinGWbing++.exe -fdiagnostics-color=always -g C:Usersjohancu-workspaceTEstTest.cpp -o C:Usersjohancu-workspaceTEstTest.exe
C:UsersjohanAppDataLocalTempcck3aAZo.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).

2

Answers


  1. 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.

    Login or Signup to reply.
  2. According to your build info:

    C:MinGWbing++.exe -fdiagnostics-color=always -g C:Usersjohancu-workspaceTEstTest.cpp -o C:Usersjohancu-workspaceTEstTest.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:MinGWbing++.exe -g C:Usersjohancu-workspaceTEstTest.cpp C:Usersjohancu-workspaceTEstOther.cpp -o C:Usersjohancu-workspaceTEstTest.exe
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search