build error when separating c++ code

98 Views Asked by At

I have recently made a little example in order to practice separating C++ code in .h and .cpp files using Geany. The code compiles without issue, but the following error occurs when I build:

g++ -std=c++11 -Wall -o "parent1" "parent1.cpp" (in directory: C:\Program Files (x86)\Geany)
C:\Users\Sabine\AppData\Local\Temp\ccnonGdW.o:parent1.cpp:(.text+0x15): undefined reference to `grandparent::grandparent(int)'
c:/mingw/bin/../lib/gcc/mingw32/4.8.1/../../../../mingw32/lib/libmingw32.a(main.o): In function `main':
i:\p\giaw\src\pkg\mingwrt-4.0.2-1-mingw32-src\bld/../mingwrt-4.0.2-1-mingw32-src/src/libcrt/crt/main.c:91: undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status
Compilation failed.

The source files:

parent1.h:

#ifndef PARENT1_H
#define PARENT1_H

#include "grandparent.h"

class parent1 :public grandparent
{   private:
       int i ;
    public:
       parent1(int p1a, int p1b, int p1c);
};

#endif

parent1.cpp:

 #include "parent1.h"
    #include "grandparent.h"
    #include <iostream>
    #include <string>
    using namespace std;

    parent1::parent1(int a, int b, int c)
    : grandparent(a)
    {}

Hi thanks for the quick replies.

Remove this line #include "grandparent.h" in parent1.cpp --- that didn`t work. ( Error: expected class-name before {-token )

grandparent.h looks like this:

#ifndef GRANDPARENT_H
#define GRANDPARENT_H
class grandparent
{   private:
        int gx; 
    public: 
        grandparent(int gx);    
};
#endif
1

There are 1 best solutions below

5
On

You need to link with the grandparent object - grandparent.o or the library it belongs to.

UPDATE: In particular you need (assuming you've already compiled grandparent.cpp):

g++ -std=c++11 -Wall -o "parent1" "parent1.cpp" "grandparent.o"

I believe that

   g++ -std=c++11 -Wall -o "parent1" "parent1.cpp" "grandparent.cpp"

will also work.