Question

I've found curios thing which I cannot explain. When I use class creation wizard in VS2013 it would create me .h and .cpp files with defined class basis.

Example header file:

#pragma once

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
};

Then I added some usings. I've included headers with these namespaces in stdafx. std and sf from SFML are used in my app:

#pragma once

using namespace std;
using namespace sf;

class SomeClass
{
public:
    SomeClass();
    ~SomeClass();
};

And everything works fine. stdafx.h is not included in header file, only in .cpp.

But then I'll go with manual creation of header file(without .cpp) using same class structure:

#pragma once

using namespace std;
using namespace sf;

class SomeOtherClass
{
     public:
        SomeOtherClass();
        ~SomeOtherClass();
}

And it doesn't work. VS says that it can't find "sf" namespace, but there are no problems with "std" namespace.

And that's the thing which I want to know: why first case is valid and VS have found namespaces from precompiled headers and second case doesn't work.

Was it helpful?

Solution

Header files are never compiled alone. Only your cpp or c files are compiled and the header files are copied into them by the preprocessor when you #include them.

That means if all your cpp files where you include a header have your namespaces before the include of the header, it will work. Because the compiler will find the namespaces before compiling the code of the header in that file.

It's not good practice though. A header should work on it's own and not rely on the cpp file to do something before the include.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top