GCC not resolving automatically .cpp from .h class include

∥☆過路亽.° 提交于 2020-01-06 13:59:24

问题


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!


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/19256114/gcc-not-resolving-automatically-cpp-from-h-class-include

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!