-1

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
user3443063
  • 1,455
  • 4
  • 23
  • 37
  • Remove this line #include "grandparent.h" in parent1.cpp – Kevin Le - Khnle May 22 '14 at 18:15
  • 2
    Show the contents of grandparent.h – 001 May 22 '14 at 18:16
  • Also, writing `using namespace std;` is considered bad practice for the reasons outlined here: http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice. – djikay May 22 '14 at 18:17
  • @Khnle - how would removing the inclusion in cpp help? Preprocessor guards prevent it from being a problem. – Andy May 22 '14 at 18:26
  • @ssell Compilation would have failed if this were the case - OP said that compilation is successful but 'build' (presumably link) is failing. – Andy May 22 '14 at 18:27
  • 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 – user3443063 May 22 '14 at 18:37

1 Answers1

3

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.

Andy
  • 1,663
  • 10
  • 17