user3742309
user3742309

Reputation: 195

mingw32/bin/ld.exe ... undefined reference to [class] ... collect2.exe: error: ld returned 1 exit status

Problem description while I am trying to move my code from Linux to Windows:

Relevant code samples:

Person.hpp

class Person
{
    public:
        Person(const string& iName, 
                const list<string>& iContactDetails,
               ); 

        virtual ~Person(); 
        ...

Main.cpp

#include "Person.hpp"
...
int main()
{
...
Person myPerson = Person (myName, myContactDetails); //here is the linker problem
...
return 0;
}

Compilation command:

standalone

g++ -o MyProgram.exe Main.cpp -Wall

Makefile (tried even CC instead of CXX, or LDFLAGS=-lgdi32 instead of CXXFLAGS)

EXECUTABLE = MyProgram.exe

CXX = "C:\MinGW\bin\g++.exe"
CXXFLAGS = -Wall      // tried LDFLAGS=-lgdi32 as well

src = $(wildcard *.cpp)
obj = $(src:.cpp=.o)

all: myprog

myprog: $(obj)
    $(CXX) -o $(EXECUTABLE) $^ $(CXXFLAGS)

.PHONY: clean
clean:
    del $(obj) $(EXECUTABLE)

Error:

c:/mingw/bin/../lib/gcc/mingw32/8.2.0/../../../../mingw32/bin/ld.exe: C:\Users\....:Main.cpp:(.text+0x124c): undefined reference to `Person::~Person()'
collect2.exe: error: ld returned 1 exit status

As a summary, I encounter Linker problems during the MinGW G++ compilation step:

All external entity references are resolved. Library components are linked to satisfy external references to entities not defined in the current translation. All such translator output is collected into a program image which contains information needed for execution in its execution environment.

I tried to follow other similar problems, but they are unfortunately different issues:

  1. C compiler error: undefined reference to function
  2. What is an undefined reference/unresolved external symbol error and how do I fix it?
  3. facing error in linking codes in c++

How should I change my Makefile or my code? What flags does MinGW uses in Windows? Thank you very much

Upvotes: 2

Views: 5688

Answers (1)

kaileena
kaileena

Reputation: 141

Same answer as I provided for How to correctly define and link a C++ class destructor to a main file?

I had the same problem as you. Try to move your constructor and destructor definition from the cpp into the header file. This way, the linkage is well done only by running the simple g++ command that you mentioned, you do not need a Makefile for this. The includes tell your compiler where to find the definitions.

Try:

MyClass(const string& className){ _className=className };

If the definition is inside the cpp file, I get the same error as you have.

Upvotes: 1

Related Questions