Johnride
Johnride

Reputation: 8736

GCC not resolving automatically .cpp from .h class include

My issue is similar to this one but I can't figure how to fix it in eclipse.

I have a wierd behavior when compiling a small program on eclipse. When I include the .cpp file at the end of the header (and remove the include of the .h in the .cpp) it compiles and otherwise not.

The class I am trying to include is in a separate project and that project is properly linked.

Here is an example:

In project Sources

file myclass.h

#ifndef MYCLASS_H_
#define MYCLASS_H_

namespace lol
{
class myclass{ public // definitions... }
}
//#include myclass.cpp //**works when I uncomment this**
#endif

file myclass.cpp

#include "myclass.h" // ** does not work unless I include my .cpp (unity build like) **
                     // and I don't want to include .cpp files
namespace lol{ // not funny

myclass::myclass(){
} //code ... code
}

In other project mainFile.cpp

#include "myclass.h" // works only if I include myclass.cpp at the end of myclass.h

using namespace lol;
int main(){
    myclass obj = myclass(); // gives undefined reference to lol::myclass::myclass()
}

I could fix this by building everything from a makefile which is a solution I like but I need to use eclipse, sadly.

Any suggestions?

Thanks!

Upvotes: 0

Views: 194

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

I'd say if your .cpp is seen from eclipse auto makefile generation it takes it as source (translation unit) and adds it to the sources list.

If you want to include inline definitions (once), you should use different file extensions (e.g. .tcc, .icc).

You could also try to exclude it from the project's resource configurations (Right Click the .cpp, choose 'Resource Configurations -> Exclude from build').

Another option is to change the project type to 'Makefile project' and maintaining the makefiles on your own.

Upvotes: 0

kfsone
kfsone

Reputation: 24249

You are missing a "#endif" at the end of the include file.

Use "#pragma once" instead.

// .h file
#pragma once

namespace lol
{
    class foo {};
}

// end of file

See my explanation of the compilation-unit and pipeline here.

Upvotes: 1

Related Questions