below is my program. I want to link the implementation file to main function.


// implementation file
// imp.cpp
#include "myClass.hpp"
#include <iostream>

using namespace std;

int display(void)
{
cout<<"hello"<<endl;
}


// main function
//main.cpp
#include "myClass.hpp"

int main()
{
myClass sub;
sub.display();
return 0;
}

// header file.
//myClass.hpp
class myClass
{
public:
void display();
};


I compiled it using this syntax:
1.) g++ -c main.cpp
2.) g++ -c imp.cpp
3.) g++ main.o imp.o -o main.exe

the error displayed was:

In function `main':main.cpp:(.text+0x23): undefined reference to `myClass::display()'
collect2: ld returned 1 exit status

What this means? how could i remedy this problem?
please help me...

tnx in advance..

Dani AI

Generated

Short diagnosis: the linker error "undefined reference to myClass::display()" means the class member was declared but never defined with the correct class scope/signature. In the provided imp.cpp a free function display (and with the wrong return type) is being compiled instead of myClass::display. That is why the linker cannot find the symbol. Both points made by (return type must match) and (compile both sources together or link the objects) are correct, but the crucial missing piece is the scope qualifier on the definition.

Correct member definition (put this in imp.cpp, not in the header):

void myClass::display()
{
    std::cout << "hello" << std::endl;
}

Make sure myClass.hpp declares void display(); and that imp.cpp includes the header and #include <iostream>. Avoid using namespace std; in headers; keep it (if used) inside the .cpp.

Compilation options: either compile-and-link in one step

g++ main.cpp imp.cpp -o main

or the multi-step object flow

g++ -c main.cpp
g++ -c imp.cpp
g++ main.o imp.o -o main

Extra tips: add an include guard (#ifndef/#define or #pragma once) to the header to avoid duplicate definitions, ensure prototypes and definitions match exactly (same return type, parameters, const-qualification), and if linker errors persist inspect object symbols with nm and demangle with c++filt to confirm whether myClass::display was emitted. This addresses the undefined-reference root cause while reinforcing the return-type and compile/link suggestions already posted.

Recommended Answers

All 2 Replies

In your header file you declared display as a void function...in your imp.cpp file you called it an int function...it should be a void function...

Hmm... didn't read my advice in your previous thread regarding this issue?

The actual source files are fed to g++:

g++ main.cpp imp.cpp -o main.exe

[edit] and yeah, having the same return type helps...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.