C ++: Adding ".cpp" implementations in Visual Studio and GCC

4

In C ++, what you observe in a quick internet search is the guideline that only ".h" files should be included. A sample of this can be seen here and especially here .

In Visual Studio, adding only ".h" with #include ... is not a problem as long as the ".cpp" deployment files are included in the project. This ensures that they will be compiled and there will be a valid reference for the methods of the class. However, this does not seem to be the case for GCC (g ++). See the code below:

Mt.h

#ifndef MT_H
#define MT_H

namespace Subsistema {
  class Mt {
  public:
    int soma(int i, int d);
  };
}
#endif

Mt.cpp

#include "Mt.h"

namespace Subsistema {
    int Mt::soma(int i, int d) {
    return i + d;
  }
}

main.cpp

#include <iostream>
#include "Mt.h"

int main(int argc, char *argv[]){
  Subsistema::Mt * t = new Subsistema::Mt();

  std::cout << "Soma: " << t->soma(3, 5) << std::endl;

  delete t;

  return 0;
}

The above code will compile perfectly in Visual Studio even though there is no #include Mt.cpp , as long as it is included in the project. But it will NOT do it in g ++ , with the following error message:

  

/tmp/ccQVvF4r.o: In function 'main':

     

main.cpp: 7: undefined reference to 'Subsystem :: Mt :: soma (int, int)'

     

collect2: error: ld returned 1 exit status

This error could easily be resolved by adding the #ifdef __GNUC__ macro, as follows:

#ifndef MT_H
#define MT_H

namespace Subsistema {
  class Mt {
  public:
    int soma(int i, int d);
  };
}

#ifdef __GNUC__
#include "Mt.cpp"
#endif

#endif

But the point is, this is a solution, but is it the right solution (best practice) for the situation? I need a solution, as far as possible, independent of the compiler used.

NOTE: This question is closely related to How to include header and cpp without resulting in LNK2005 error in Visual Studio     

asked by anonymous 05.10.2017 / 03:43

1 answer

1

The error message is not a compilation error. This is an linkage error:

/tmp/ccQVvF4r.o: In function 'main':
main.cpp:7: undefined reference to 'Subsistema::Mt::soma(int, int)'
collect2: error: ld returned 1 exit status

It means that linker is not found the object file containing the Subsistema::Mt::soma(int, int) method implementation.

The Mt.cpp must be passed as a parameter to the compiler and not included by means of the #include directive.

This should compile your program without errors:

$ g++ main.cpp Mt.cpp -o teste
    
05.10.2017 / 14:24