Objects in other namespace not found without include, files otherwise identical - c++

I have two functionally identical header files, one of which produces errors for no discernible reason. I must have done something wrong in creating the new (broken) file, but I can't figure out what.
My IDE is Xcode. The project is compiled for Objective C++ using Apple LLVM Compiler 4.1, but the section of code in question is all pure C++, no Objective C.
Here's some code:
NamespaceA.Common.h
#include "../NamespaceB/Common.h"
#include "WorkingClass.h"
#include "BrokenClass.h"
...
../NamespaceB/Common.h
#ifndef NamespaceBCommon
#define NamespaceBCommon
namespace NamespaceB
{
...
}
...
#include "Superclass.h"
...
WorkingClass.h
#ifndef NamespaceA_WorkingClass
#define NamespaceA_WorkingClass
namespace NamespaceA
{
class WorkingClass : public NamespaceB::Superclass
{
public:
WorkingClass();
~WorkingClass();
};
}
#endif
BrokenClass.h
#ifndef NamespaceA_BrokenClass
#define NamespaceA_BrokenClass
// If I don't have this line I get errors. Why?? !!!!!
// This file is exactly identical to WorkingClass.h
// as far as I can tell!
//#include NamespaceA.Common.h
namespace NamespaceA
{
// Parse Issue: Expected class name !!!!!
// Semantic Issue: Use of undeclared identifier 'NamespaceB'
class BrokenClass : public NamespaceB::Superclass
{
public:
BrokenClass();
~BrokenClass();
};
}
#endif
Thank you.

You need to include all of the files that include namespaces and classes that you reference in your code. So, because you reference NamespaceB::Superclass in your BrokenClass.h, you need to be sure to include the file that declares that. In this case, including NamespaceA.Common.h (hopefully) solves this problem, because it includes the file where NamespaceB is included.
As for why you don't have to include NamespaceA.Common.h in your WorkingClass.h, I suspect it's because you just happen to have ../NamespaceB/Common.h included somewhere else.

I found the problem. WorkingClass.cpp was including NamespaceA.Common.h and not including its own header file, rather than including the common file in the header and then including its own header file in the cpp.
I managed to miss the #include in WorkingClass.cpp because I just assumed it was only including WorkingClass.h and not NamespaceA.Common.h.
So in short:
WorkingClass.h
// Class goes here
// No includes
WorkingClass.cpp
// Notice it does not include WorkingClass.h for whatever reason
#include "NamespaceA.Common.h"
NamespaceA.Common.h
#include "../NamespaceB/Common.h"
#include "WorkingClass.h"
#include "BrokenClass.h"
#include "EveryOtherClass.h" ...
BrokenClass.h
// Class goes here
// No includes
BrokenClass.cpp
#include "BrokenClass.h"
// Oh no! Where's NamespaceA.Common.h?
I'm not a big fan of this include scheme, but I'll live with it since it's a large project that I don't want to make sweeping changes to.

Related

Is it possible to add an include directive inside of a class definition?

I am currently working on a project where we have a shared set of headers. Now we want add some private fields without having to put those declarations directly in the shared headers.
Someone brought up the following:
namespace something {
class Foo {
public:
Foo();
void doFoo();
private:
#if __has_include("foo_private.hpp")
#include "foo_private.hpp"
#endif
};
}
Inside the _private.hpp headers we would then place the private fields for that class. When there are only default datatypes (int, bool, etc) this works fine(ish). But as soon as you put an include inside the _private.hpp file, for example #include everything breaks.
It is giving the following error expected unqualified-id before ‘namespace’ which as I understand is quite logical, since you're trying to define a namespace inside of a class.
Example _private.hpp file
#ifndef DUMMY_PRIVATE_TEMPLATE_INCLUDES_FOO_PRIVATE_HPP
#define DUMMY_PRIVATE_TEMPLATE_INCLUDES_FOO_PRIVATE_HPP
#include <string>
int mySecretNumber;
std::string mySecretString;
#endif
Now my question is, is there any way to trick the preprocessor, or somehow get the same results with a different solution?
namespace something {
class Foo {
public:
Foo();
void doFoo();
private:
#if __has_include("foo_private.hpp")
#include "foo_private.hpp"
#endif
};
}
If that code is including a file that looks like this:
#ifndef DUMMY_PRIVATE_TEMPLATE_INCLUDES_FOO_PRIVATE_HPP
#define DUMMY_PRIVATE_TEMPLATE_INCLUDES_FOO_PRIVATE_HPP
#include <string>
int mySecretNumber;
std::string mySecretString;
#endif
Then you end up with this (though in reality, the #includes themselves would resolve to the contents of <string>, etc.):
namespace something {
class Foo {
public:
Foo();
void doFoo();
private:
#ifndef DUMMY_PRIVATE_TEMPLATE_INCLUDES_FOO_PRIVATE_HPP
#define DUMMY_PRIVATE_TEMPLATE_INCLUDES_FOO_PRIVATE_HPP
#include <string>
int mySecretNumber;
std::string mySecretString;
#endif
};
}
Perhaps that shows your issue? You're including "string" in the middle of your class, but it needs to be included at the global namespace scope of your file.
Instead, include string at the top of the outer header, don't use include guards in the private header, and only put the body of the code you want pasted into your class into that private header. For that reason, you might not call it a ".hpp" file but something else to make it clear it's not a normal header.
Additionally, the __has_include feature seems dubious, because if your private header is missing you probably do not want it to compile to an empty class.
Worse, if you compile some translation unit that finds the header, and then compile another translation unit that does not find the private header, you will end up with two different definitions of your class, violating the One Definition Rule -- which is undefined behavior, no diagnostic required. Really nasty stuff (assuming your builds succeeds at all.)
I'm not a big fan of this kind of hiding, as it will make it hard for editors to properly show your code, to colorize and index your private header, or otherwise work with the code in a normal way. You might consider looking at the PIMPL idiom for hiding the implementation of a class in its .cpp file, so users of the header do not have to see it at all.

If you include something in the .h file Do you have to include the same thing again?

So I am just wondering if you #include something in a for example header.h file:
For example this is called header.h:
#include <vector>
#include <iostream>
#include <somethingElse>
So if for example I make a file called something.cpp Do I need to put all those include statements again?
#include "header.h"
// If I include #header.h in this file. Do the #include carry over to this file. Or do they not
I am wondering because whenever I include <vector> something in my .h file the #include statements that I used previously in the .h file always turn grey which means they are not used. Is it because I used it in the .h file? Its not a problem or anything I am just curious.
You don't need to include those headers again because your compiler can find those headers. You can also try to read and understand the makefile (or CMakeList) which will help.
Try always to avoid "Multiple file inclusion" via using inclusion guard or #pragma once in order to prevent the multiple file inclusion.
To include file means that the content of the file will be added to the very place you wrote include.
Here's an example:
// header.h
const int vlaue = 10;
const int value2 = 0;
// main.cpp
#include "header.h"
#include "header.h"
Above the content of "header.h" is added twice to main.cpp.
Do you know what is the result? It's a compile-time error complaining of redefinition of value and value2.
In the above example I think green programmers don't get trapped by it but it is just an explanation, So what I talk about is when a huge program where many header files and many source files and some files include others then it'll be so difficult to track the right file inclusion.
The workaround that is to use inclusion guards or pragma once eg:
Let's modify our header.h to look like:
// header.h
#ifndef MY_HEADER_H
#define MY_HEADER_H
const int vlaue = 10;
const int value2 = 0;
#endif
Now in main.cpp:
#include "header.h"
#include "header.h"
#include "header.h"
The code above works fine and no duplicate of header content is added to main.cpp. Do you know why? It's the magic of Macro there. So at first time the pre-processor checks whether a macro has been already defined with the name MY_HEADER_H or not and for sure for the first time it is not defined so the content is added. The second and so on the condition fails because the macro is already defined thus the content of header.h will not be added to where it is called.
The draw back of inclusion guard is if you have a macro with same name as the inclusion guard thus it is already defined so the content will never be added (empty content). Thus you get a compile-time error:
value, `value2` undeclared identifiers.
The second solution is using pragma eg:
Let's modify our header.h file:
// header.h
#pragma once
const int vlaue = 10;
const int value2 = 0;
// main.cpp
#include "header.h"
#include "header.h"
The code above works correctly so no multiple inclusion of header.h That is because of the magic of pragma once: which is a non-standard but widely supported pre-processor directive designed to cause the current source file to be included only once in a single compilation. Thus, #pragma once serves the same purpose as include guards, but with several advantages, including: less code, avoidance of name clashes, and sometimes improvement in compilation speed.
Finally you should include header wherever their content is used eg:
// Shape.h
class Shape{
// some code here
};
// Cube.h
#include "Shape.h"
class Cube : public Shape{
// some code here
};
// Cuboid.h
// #include "Shape.h"
#include "Cube.h" // So here the Shape.h is added to Cube.h and Cube.h is added here.
class Cuboid : public Cube{
// some code here
};
As you can see above the content of Shape.h is added to Cuboid.h indirectly because it is added to Cube.h and cuboid.h includes Cube.h so it is added to it. So without inclusion guards or pragma once if you include the two headers in one source file you get duplicate content there.

Undefined base class, though includes present

Forehand I'd like to mention I'm fairly new to C++ programming and that I'm using Ogre3D as framework (for school project reasons).
I have a class Player which inherits from the GameObject class. When trying to build the project I'm confronted with the following error:
Error C2504 'GameObject' : base class undefined - player.h (9)
Which would imply the GameObject class is undefined within the player class' header file. However I have in fact included the GameObject header file in that of the Player (see code below). I am aware circular including is happening in the code. However if I leave out these includes I get a whole list of different errors on which I'm not sure how or why they occur:
I've been stumped on this problem for a few days now and haven't found any solutions around the Internet as of yet (CPlusPlus article I've mainly been consulting: http://www.cplusplus.com/forum/articles/10627/).
The source files for the below listed header files only include their respective header files.
Player.h
#pragma once
#ifndef __Player_h_
#define __Player_h_
#include "GameObject.h"
class Player : public GameObject {
// ... Player class interface
};
#endif
GameObject.h
#pragma once
#ifndef __GameObject_h_
#define __GameObject_h_
#include "GameManager.h"
// Forward declarations
class GameManager;
class GameObject {
// ... GameObject class interface
};
#endinf
The GameObject header includes the GameManager as can be seen.
GameManager.h
#pragma once
// Include guard
#ifndef __GameManager_h_
#define __GameManager_h_
// Includes from project
#include "Main.h"
#include "Constants.h"
#include "GameObject.h" // mentioned circular includes
#include "Player.h" // "
// Includes from system libraries
#include <vector>
// Forward declarations
class GameObject;
class GameManager {
// ... GameManager interface
};
#endif
To top it of there is the Main class which header file looks like the following:
Main.h
// Include guard
#ifndef __Main_h_
#define __Main_h_
// Includes from Ogre framework
#include "Ogre.h"
using namespace Ogre;
// Includes from projet headers
#include "BaseApplication.h"
#include "GameManager.h"
// forward declarations
class GameManager;
class Main : public BaseApplication
{
// ... Main interface
};
#endif
With all the reading I did on the subject and other individuals with the same error I'd figure I would be able to figure it out but yet to no avail. I hope someone can take the time to help me out here and point out any faulty code or conventions.
I think the easiest way to fix the problem is to change your model for including header files. File A.h should only include B.h if B.h defines a symbol that is used (directly) in A.h. It's also generally a bad idea to put a using clause in a header file - let the programmer of the client code make that determination. Drop forward declarations for classes unless they are absolutely necessary; there's no need for the class GameManager right after #include "GameManager.h". I suspect something else is wrong with the code, but the forward declarations for the classes are hiding that problem. If changing the includes does not fix the problem, start with a single .cpp file that includes the "simplest" header (the one that doesn't depend on any others) and build up to the full set of includes.

Header-only library design - include directives

I'm creating an header-only C++11/14 library and I'm not sure on how I should handle #include directives between library files.
Should I try to group as many #include directives as possible in the user-oriented module header file or should internal files include files they require (sometimes repeating the same includes)?
Approach A:
In this approach, the module header file includes all required dependencies and then includes the implementations. The implementations' header files do not include anything by themselves.
// Library/Module/Module.hpp
// This file is intended to be included by the user in his projects.
#ifndef MODULE
#define MODULE
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
#include "Library/Module/Impl/Class1.hpp"
#include "Library/Module/Impl/Class2.hpp"
#endif MODULE
-
// Library/Module/Impl/SharedDependency.hpp
#ifndef SHARED_DEPENDENCY
#define SHARED_DEPENDENCY
inline void sharedFunc() { }
#endif
-
// Library/Module/Impl/Class1.hpp
#ifndef CLASS1
#define CLASS1
// No need to include "SharedDependency.hpp", as it will be included by
// the module header file. Same applies for <vector>.
struct Class1
{
std::vector<int> v;
Class1() { sharedFunc(); }
};
#endif
-
// Library/Module/Impl/Class2.hpp
#ifndef CLASS2
#define CLASS2
// No need to include "SharedDependency.hpp", as it will be included by
// the module header file. Same applies for <vector>.
struct Class2
{
std::vector<int> v;
Class2() { sharedFunc(); }
};
#endif
Approach B:
In this approach, the module header file includes only the implementation headers. If the implementation headers require additional includes, they include the files themselves (recursively), sometimes repeating the same include.
// Library/Module/Module.hpp
// This file is intended to be included by the user in his projects.
#ifndef MODULE
#define MODULE
#include "Library/Module/Impl/Class1.hpp"
#include "Library/Module/Impl/Class2.hpp"
#endif MODULE
-
// Library/Module/Impl/SharedDependency.hpp
#ifndef SHARED_DEPENDENCY
#define SHARED_DEPENDENCY
inline void sharedFunc() { }
#endif
-
// Library/Module/Impl/Class1.hpp
#ifndef CLASS1
#define CLASS1
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
struct Class1
{
std::vector<int> v;
Class1() { sharedFunc(); }
};
#endif
-
// Library/Module/Impl/Class2.hpp
#ifndef CLASS2
#define CLASS2
#include <vector>
#include "Library/Module/Impl/SharedDependency.hpp"
struct Class2
{
std::vector<int> v;
Class2() { sharedFunc(); }
};
#endif
What is the best approach?
Intuitively, I think Approach A is the best, as it avoids repeating the same includes and makes clear what files need to be included before the other files. The biggest drawback is, though, that syntax highlighting stops working in my IDE (QT-Creator), in the implementation files with no include directives.
EDIT:
This question was voted to be closed for the reason "opinion based". I disagree, because in a large header-only project such as my library including files may take a lot of compile time. Therefore, approach A may be faster than approach B, or the opposite.
Approach B is actually the best approach, since including the same header multiple times does not produce any observable compilation time increase, but is advantageous for the following reasons:
Modern IDEs can use libclang or proprietary solutions to parse the #include directives and provide code-aware syntax highlighting and autocompletion features.
As mentioned by TemplateRex, it becomes much easier to verify a sane build process. CMake, for example, provides macros that automatically generate a test for every header.
As mentioned by Alf, it is good practice to have every file include all the headers it depends on - users of the library can then "cherry-pick" header files they require, instead of being unexpectedly force to manually include a parent header.

Compile error when I use C++ inheritance

I am new to this website and I am trying a simple inheritance example in C++.
I checked my code lots of times and I really see nothing wrong with it, however the compilers gives me errors:
my code:
#ifndef READWORDS_H
#define READWORDS_H
using namespace std;
#include "ReadWords.h"
/**
* ReadPunctWords inherits ReadWords, so MUST define the function filter.
* It chooses to override the default constructor.
*/
class ReadPunctWords: public ReadWords {
public:
bool filter(string word);
};
#endif
And the messages I get from the compiler:
ReadPunctWords.h:11: error: expected class-name before '{' token
ReadPunctWords.h:13: error: `string' has not been declared
ReadPunctWords.h:13: error: ISO C++ forbids declaration of `word' with no type
Tool completed with exit code 1
I am really not sure where I get it wrong as it looks just fine to me?
Thank you for any mistakes you might spot.
You need to include string:
#include <string>
That said, don't use using namespace! Especially at file-scope, and definitely not in a header file. Now any unit that includes this file is forced to succumb to everything in the std namespace.
Take that out, and qualify your names:
bool filter(std::string word);
It's arguable more readable, too. Additionally, you should take your string as a const&:
bool filter(const std::string& word);
To avoid having to copy the string unnecessarily. Lastly, your header guards seem off. Should they be changed? As of now, they seem like the same ones that would be used in your other header, which might effectively stop it from being included.
If you define READWORDS_H and then include ReadWords.h, and if that also has:
#ifndef READWORDS_H
#define READWORDS_H
Then nothing in that file will be processed. If that's the case, ReadWords as a class won't be defined, and you cannot inherit from it. Your guard should probably be:
READPUNCTWORDS_H
You need to include <string> and specify the namespace:
#include <string>
using namespace std;
Also, your include guard should probably be named READPUNCHTWORDS_H rather than READWORDS_H.
Edit: On second thought, GMan is right about not putting using namespace in a header file - qualify the string with std::string instead.
This particular form of error is often caused by a type not being defined (at least when the code looks syntactically correct), in this case probably the class ReadWords but maybe also std::string.
You need to include to get std::string, as other posters have written, but also your guard
#ifndef READWORDS_H
#define READWORDS_H
almost certainly conflicts with the guard in ReadWords.h. You need to make sure your guards are distinct in different header files otherwise you will get conflicts like this. You should change the guard to something like
#ifndef READPUNCTWORDS_H
#define READPUNCTWORDS_H
// ...
#endif
In fact, it's better to have even more verbose guards to make sure they don't conflict. We use guards of the form
#ifndef MODULE_OR_PATH_FILE_H_INCLUDED
#define MODULE_OR_PATH_FILE_H_INCLUDED
// ...
#endif
This ensures different modules or libraries with similarly named headers don't conflict, the INCLUDED thing at the end is my own particular foible that makes the guard slightly more readable.
It's also bad practice to place a "using" declaration in a header file, because it places (potentially unwanted or conflicting) symbols in the global namespace everywhere you include the header. Personally, I prefer to retain the namespace for clarity or alias it in cpp files if it's a long one, for example
namespace fs = boost::filesystem;
also looks like something wrong with ReadWords class def (message for line 11)- we need to see .h file
aha - the sentinial def you use prevents the readwords.h include being read
you need
#ifndef _READPUNCTWORDS_H
#define _READPUNCTWORDS_H
I also suspect the include guards. If they are named the same way in both header files, the result should be something like the following when ReadWords.h is pasted into ReadPunctWords.h.
#ifndef READWORDS_H // Is READWORDS_H defined? No, proceeding
#define READWORDS_H // Now it is defined
// Contents of ReadWords.h is pasted in here
#ifndef READWORDS_H // Is READWORDS_H defined? Yes, ignoring the contents of ReadWords.h (skipping til #endif)
#define READWORDS_H
class ReadWords { ... }; // This is never seen by the compiler as the preprocessor removed it
#endif
class ReadPunctWords: public ReadWords { // Error: ReadWords isn't declared...
public:
bool filter(string word);
};
#endif