0

env:

OS: Windows 10

compiler: cygwin g++

To demonstrate the problem I meet, I create three files, main.cpp, class.h and class.cpp, all of which are located in the same dir.

main.cpp

#include "class.h"

int main(){
    Class c;
    c.fun();
    return 0;
}

class.h

#ifndef class_h
#define class_h

class Class{
public:
    int i;
    void fun();
};

#endif

class.cpp

#include <class.h>

void Class::fun(){
    i++;
    i++;
}

and the way I compiled my main.cpp is:

g++ main.cpp

however, it generated error like this:

C:\Users\xxx\Desktop\temp>g++ main.cpp
/usr/lib/gcc/x86_64-pc-cygwin/9.3.0/../../../../x86_64-pc-cygwin/bin/ld: /cygdrive/c/Users/xxx/AppData/Local/Temp/cco3V0Lq.o:main.cpp:(.text+0x15): undefined reference to `Class::fun()'
/cygdrive/c/Users/xxx/AppData/Local/Temp/cco3V0Lq.o:main.cpp:(.text+0x15): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Class::fun()'
collect2: error: ld returned 1 exit status

Could anyone help me.... thanks in advance ;-)

Community
  • 1
  • 1
Jhin Koo
  • 22
  • 3
  • 4
    You compile `main.cpp`, but not `class.cpp` – Igor Tandetnik May 31 '20 at 03:00
  • 2
    `g++ main.cpp class.cpp` – selbie May 31 '20 at 03:01
  • Note that not initializing `i` before writing to it is Undefined Behavior. Not that that is necessarily your problem here. Just something to look out for. –  May 31 '20 at 03:20
  • 1
    Does this answer your question? [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix), in particular [this answer](https://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix/12574400#12574400) – JaMiT May 31 '20 at 03:47

0 Answers0