Using namespace to avoid name collisions - c++

I was compiling one of the projects I work with, this time with VS2010, just to find out that one of the includes in windows.h has a typedef INPUT which was clashing with an export const string in the code I already have.
//winuser.h (line: 5332)
typedef struct tagINPUT {
DWORD type;
union
{
MOUSEINPUT mi;
KEYBDINPUT ki;
HARDWAREINPUT hi;
};
} INPUT, *PINPUT, FAR* LPINPUT;
//foo.h
//stuff here
extern FOO_DLL_API const string INPUT;
Now, I don't use INPUT in the offending .cpp (and I do not own most of the code), and trying to minimize the impact, I did the following:
//myfile.cpp
#include <foo.h>
namespace windowsLib { //I added this
# include <windows.h>
}
using namespace windowsLib;
So far, this approach is working fine, but I wanted to ask you if you see potential problems with this approach, or if you have a better suggestion.
Edit:
I appreciate all the comments and explanations on why this is a bad idea. What I get from your comments is that I should change foo.h and put the contents into a namespace. However, by doing that, I would be affecting dozens of files, and some more, which will now require namespace qualifications.
Is there a way to do this "the right way" without touching all those files?
If I was the owner of the code, I would do this change and be done with it, but I have to propose a solution and get it approved and assigned to someone, etc. So it will be easier if the change is minimal.
Edit 2:
My final proposal was to split the class in two as follows:
//stub.cpp
#include <windows.h>
//Implementation of wrapper methods
//stub.h
class stub {
//public wrapper methods
}
//myfile.cpp
#include <stub.h>
#include <foo.h>
I'm accepting Benlitz answer since that suggestion would also solve the problem with the current minimal impact constrains I currently face. However, I thank you all for your comments.

Not only is it not allowed by the language (assuming standard headers will be included inside a namespace), there is also the problem of calling any functions declared in <windows.h> and finding that the linker will look for them in namespace windowsLib.
Just doesn't work!

This seems like a bad idea at least.
1) If that's actually your code, there's no benefit from adding the namespace, since you have using namespace windowsLib; on the next line. Won't INPUT be ambiguous anyway?
2) You might include other headers that use stuff from windows.h and won't use the correct symbols. Imagine including a header that defines a function that returns INPUT. How's that gonna work out?
I suggest you play it safe and just rename your type.

It is a bad idea as explained in other answers. Here is an idea that might help you fix your issue:
//myfile.cpp
#define INPUT UnusedSymbol
#include "foo.h"
#undef INPUT
#include "windows.h"
This might work because INPUT is an extern variable in foo.h, so neither the compiler nor the linker would care about it as long as you don't use it in myfile.cpp. UnusedSymbol is a dummy name, you can write whatever name is not used in your source.

Putting a namespace around windows.h sounds dangerous to me. It probably would hide stuff you need. Except you import the namespace in the next line anyway.
I would sooner put the namespace around foo.h:
namespace fooLib {
#include "foo.h"
}
using fooLib;
I guess this just shifts the problem from OS code to foo code but that seems safer to me.
Another approach might be to build a wrapper around foo that calls foo functions and returns foo globals in a separate little wrapper library. One that didn't need windows.h. This wrapper you might put in a namespace to prevent this from happening again.
I'm assuming here that you don't have the ability to rename things in foo.h or put the fooLib namespace around stuff inside foo.h.
If you can touch foo.h it would be better to rename INPUT in foo.h or put foo.h stuff in a namespace of its own. I think a fooLib namespace would have great (obvious) benefit.

Related

Which of these two is the proper way to implement a header?

Should you include #include the header of your function declaration in the source file where you define the function?
I've tried both and it seems to work either way. I was wondering if either way is preferred or if one might cause an error in a different compiler
//header.h
#ifndef HEADER_H
#define HEADER_H
int squareVal (int);
#endif
//squareVal.cpp
//should I #include "header.h" here as well?
int squareVal (int val){
return (val*val);
}
//main.cpp
#include"header.h"
using namespace std;
int main(){
cout << squareVal(2) << endl;
}
Both ways seem to work. From my testing and research it sounds like the linker is able to find squareVal.cpp regardless of including the header in that file or not.
Use the #include directive. Put it at the top, in front of any other #include directives. That way, if there's a mistake in the header, the compiler will be more likely to find it. In particular, if you declare the function differently from the way you define it, the compiler will notice. If you don't pull in the header, translation units that use that header will see a different signature from the one that's been defined, and you'll get errors when you try to link. It's much easier when you see the problem early.
Whether it makes a difference, depends on the contents of the header.
In this specific case, because a function definition does not require a previous function declaration, the #include in squareVal.cpp is not (and never will be) necessary.
However, imagine if the header contained more than the function declaration? What if it defined some types needed by the function? What if it defined some constants needed by the function definition? Then you'd need an #include.
It is considered good practice to #include regardless, because then you do not need to think about this, and doing so is effectively free.
The compiler simply puts the WHOLE code from the header right where you insert the #include "header.h". So in this example, the declaration is before the definition of the function and it does nothing bad.

C++ header inclusions

Hello I'm new to C++ so bear with me, I'm making a header for a class and I just want to know if I plan on making an object from another class in this one should I include that in the header? for example
class myClass1{
public:
"constructor and methods here"
private:
OtherClass oc;
"other variables here"
};
I know this is a pretty simple question but I can't seem to find the answer anywhere. Any help would be appreciated!
Since as you say that you are new at C++, this might seem a bit overkill for your immediate needs. Keep in mind what I'm trying to teach you is not how to hack this thing up right now, but good coding skills that will transfer to future projects and real work.
A stretch goal, and a general rule of thumb that I would recommend is:
In a header file, #include nothing, or as close to nothing as is
possible.
Why? There are at least two reasons.
First, it keeps compiles fast. This is nice, but not the real reason. The real reason is:
Second, it reduces interdependence between modules and hard couplings. An interdependence between modules is an easy thing to create, and a very difficult thing to break when it becomes a problem.
Contrary to the other answers posted here, no, you do not need to #include OtherClass's header file in this header file. This assertion yields two questions:
How is it possible to not include the header?
Why would you not include the header, even if it is possible not to?
In order:
The header file doesn't need to know anything about the definition of OtherClass. Only the translation unit does. The TU needs to know the definition of OtherClass before it can define MyClass1, but that is handled simply. Consider:
OtherClass.h:
#ifndef OTHERCLASS_H
#define OTHERCLASS_H
class OtherClass
{
};
#endif
MyClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
class MyClass
{
public:
OtherClass mOC;
};
#endif
main.cpp:
#include <cstdlib>
#include "OtherClass.h"
#include "MyClass.h"
int main()
{
MyClass mc;
}
The Translation Unit here is main.cpp and everything it #includes. The whole package. Since you do not compile header files directly (eg by themselves), headers are not translation units.
I suggest that what I propose above is better than adding:
#include "OtherClass.h"
to MyClass.h because it reduces the interdependence between the two objects.
This obviously isn't a concern right now, or in a toy program such as this. It becomes an issue later, in large & complicated codebases when you try to make changes to underlying classes. At those times, breaking these interdependancies becomes exceedingly difficult and maybe impossible depending on how much forethought you have given your design. This becomes a lesson learned with great difficulty.
Yes. If oc was a pointer or a reference, then you could get by with just a forward declaration (which appears above the class statement):
class OtherClass;
class myClass1 {
...
The include statement is needed because the compiler needs to know the details of OtherClass to define myClass1.
Yes include using #include "OtherClass.h". If you were using a system header or maybe something from STL, you would use: #include <SomeSystemHeader>

Classes interfering with each other on compile

I'm working on a C++ project.
I had a class with its function, then I realized some of those functions weren't related to that class but were just math functions so I decided to move them on to a namespace.
My first question is, what is the appropriate file extension for a c++ namespace?
I have a constants.h file where I plan on saving global constants, for example PI.
Right now:
#include <math.h>
const double PI = M_PI;
I have the namespace I talked about before, right now is called: specificMath.h
#include <stdlib.h>
#include "constants.h"
... more code
I have a gaussian.cpp:
#include "gaussian.h"
#include "specificMath.h"
#include <iostream>
... more code
This file includes a main function that right now does nothing, I just can't get the whole project to compile without a main...
I have a gaussian.h where I'm not including anything, is that wrong?
A third class, which has no attributes, just methods (again, is this wrong? or not pretty?). truncatedFunctions.cpp
#include "specificMath.h"
#include <stdlib.h>
#include "truncatedFunctions.h"
#include "gaussian.h"
using namespace specificMath;
And its truncatedFunctions.h where, again, I'm not including anything.
And a fourth class where I include
#include "margin.h" //Its header, where I'm not including anything
#include "gaussian.h"
#include "specificMath.h"
using namespace specificMath;
When I "make" it, it seems to compile fine, but when it gets to the linking part I get A LOT of errors saying that things on my margin.cpp class were first defined in truncatedFunctions.cpp
I am going crazy. I have no idea why this is happening, or how to solve it. I would really appreciate if somebody could help me out, and please, any extra piece of advice would be great since I am really trying to learn as much as I can with this project. Thanks!
When I "make" it, it seems to compile fine, but when it gets to the linking part I get A LOT of errors saying that things on my margin.cpp class were first defined in truncatedFunctions.cpp
Did you define your functions in your specificMath.h? You should only declare those functions.
For example, if your specificMath.h contains function definitions like
#ifndef COOL_STUFF_NSPC
#define COOL_STUFF_NSPC
#include <iostream>
namespace coolstuff{
void print(void){std::cout << "I'm declared in a header file." << std::endl;
}
#endif
and you are using including this file in several others, the linker is going crazy. Including means copying. And so you've got yourself coolstuff::print defined several times. The better way (and the only possible way when using self-written functions in many files) is splitting your code into a header and implementation as you did in gaussian.
// coolstuff.namepace.h
#ifndef COOL_STUFF_NSPC
#define COOL_STUFF_NSPC
namespace coolstuff{
void print(void);
}
#endif
When you include coolstuff.namespace.h it will only declare functions. And you can declare the same function several times.
// coolstuff.namespace.cpp
#include <iostream>
#include "cs.h"
void coolstuff::print(void){
std::cout << "Hello world!" << std::endl;
}
The .cpp file contains the implementation of your functions. Now your linker won't get irritated because there is only one implementation of coolstuff::print and not n (where n is the number of #include "cs.namespace.h" you used) ones.
My first question is, what is the appropriate file extension for a c++ namespace?
There is no standard namespace extension. Use .h/.cpp for header/implementation and a self-defined prefix, something like 'nmspc' or 'nsc'. It's up to you.
It's hard to tell whether you've done anything wrong in your code (because you didn't show any of it), but the first thing to try is to "clean" your build and rebuild all your code. If the compiler (don't know what you're using) for some reason didn't compile all your modified modules, then it's not surprising that the linker is having trouble.
My first question is, what is the appropriate file extension for a c++ namespace?
In C++, header files are usually .h or .hpp. It doesn't matter to the compiler.
#include "gaussian.h"
#include "specificMath.h"
#include <iostream>
In general, it's a good idea to #include stuff from the standard library first, followed by your own things.
I have a gaussian.h where I'm not including anything, is that wrong?
No. If you don't need to include anything, don't include anything.
First, use include guards for the headers.
#ifndef MYHEADER_H
#define MYHEADER_H
//header contents
#endif
This will prevent the same header from being included twice in the same translation unit.
Second, don't define uncosnt stuff in the headers:
double x = 0;
this will cause all translation units to export that symbol.
Declare the variable extern in your header and provide a definition for it in an implementation file.

Pulling C/C++ standard library into your project namespace, good idea?

I'm porting some open source code so that it can build on another c++ compiler. One of the difficulties and themes that seem to keep cropping up are implementation differences of the provided standard library by the compiler.
For example, one of the source files that I'm compiling includes <sys/types.h>. However, it gives me the following errors:
Error E2316 g:\Borland\BCC593\Include\sys/types.h 45: 'time_t' is not a member of 'std'
Error E2272 g:\Borland\BCC593\Include\sys/types.h 45: Identifier expected
After looking at the root cause of this I found that one of the main include headers of the project is including <sys/types.h> in this pattern:
project_source1.cpp:
#include "../TargetPlatform.h"
#include "project_config.h"
#include <windows.h>
namespace project_namespace {
#include "project_component/all.h"
// more project includes down here
// ...
}
project_component/all.h:
#ifndef INCLUDE_GUARDS
#define INCLUDE_GUARDS
#include <sys/types.h>
#include "project_header1.h"
#include "project_header2.h"
// and other headers etc..
// followed with class definitions and what not.
#endif
This is all well and good except for one problem, the <sys/types.h> is implemented something like this for the compiler I'm porting to:
<sys/types.h> trimmed to the essence:
namespace std {
typedef long time_t;
typedef short dev_t;
typedef short ino_t;
typedef short mode_t;
typedef short nlink_t;
typedef int uid_t;
typedef int gid_t;
typedef long off_t;
} // std
using std::time_t;
using std::dev_t;
using std::ino_t;
using std::mode_t;
using std::nlink_t;
using std::uid_t;
using std::gid_t;
using std::off_t;
And this is the cause of the compile error I'm seeing. Because the project is including <sys/types.h> inside its own namespace, things like time_t, off_t, dev_t etc get put into the scope project_namespace::std:: which is obviously not what's intended.
What's the best way to handle this? Keep in mind there could be other standard library headers defined in a similar fashion and not just sys/types.h. Are there any C++ idioms that's relevant or semi-related to this issue(or possibly even at odds with it due to the way this is implemented)? If so, how can it be reconciled?
Thanks
This is a bad idea. Do not do things this way. Put the namespace declarations inside each header file. Never have a #include directive inside the scope of a namespace.
Never is a strong word, and there are very rare cases in which you might want to do this. If the file you're #includeing also has #include directives, you almost certainly do not want to be doing this, even more so than if they didn't.
If you need to be able to easily rename your namespace or use the same header to declare the same symbols in several different namespaces depending on context, use the preprocessor to change the namespace name instead. That's extremely ugly to do, but much better than what you're currently doing.
One thing you can do as a quick and dirty solution to this is #include <sys/types.h> and any other system header that's included before the namespace declaration. This will cause the double-inclusion guards in the system header files to kick in and avoid declaring stuff inside the namespace.
I would say you need to change the offending code so that the standard types are no longer defined within project_namespace.
It seems to me you have two major issues: [1] you have a catch-all header in project_all.h and [2] it's #included inside namespace project_namespace. I'll address the latter first. If your project has things it wants to put in its own namespace, that's fine, but it should be done as follows:
// Foo.h
// includes go here
namespace project_namespace {
class Foo { ... }
}
// Foo.cpp
// includes go here
namespace project_namespace {
// Foo implementation goes here
}
... in other words, your classes' header and implementation files need to say what namespace the classes belong in, "self-namespacing" as it were. All your #includes are outside a namespace because the header file for each class declares the namespaces the class belongs to. This is the convention used by the standard library.
Now if you still want to use a project_all.h you can do so. Without the namespace -- because each header file will place its declarations in the namespace it wants to (or not).
But it would be better to dispense with project_all.h; instead, #include the header files individually and make the dependencies explicit. And if the response is "there are too many header files", that's probably a sign of a high degree of coupling between your components.
I realize this is probably not the answer you wanted, sorry ...

Declaring using statement after namespace declaration

I am writing a utility library which is made up of several "Packages". The classes in each package are contained in various namespaces. I have an idea as to how I can simplify the situation by automatically declaring using statements at the end of class declarations (see below), this will avoid having the programmer do it in a cpp file.
namespace Utility
{
class String
{
// Class Implementation
};
}
using Utility::String;
My understanding is that if the user includes the header String.h and String is in Utility then the programmer will want to use String. Obviously this could be bad if there are outside classes chain including a bunch of files which dirty up the namespace so I thought how about making it a #define instead.
namespace Utility
{
class String
{
// Class Implementation
};
}
#ifdef AUTO_DECLARE_NAMESPACE
using Utility::String;
#endif
That way, programmers that want this extended functionality can get it.
Would this a good idea or is there something I'm overlooking?
There is no point in using namespaces if you are just going to add a using declaration for each and every name declared in the namespace.
Let users of your header files decide how they want to use the headers. If someone wants to use a using declaration, let him do it in the .cpp file directly; this will make the code in that .cpp file clearer since it will be apparent where the name originated.
This seems at best pointless, and at worst annoying.
What is wrong with having developers decide which namespaces to use and what to qualify fully?
Honestly, I believe that's what the using namespace directive is for. There's no need for you to add this preprocessor mechanism, considering the using namespace directive does just that.
Couldn't you have another .h file with all your usings like my_lib_import_names.h and just #include that to get what you want?
You would probably have problem with classes not being declared but you could probably bypass it by using something like:
#ifdef UTILITY_STRING_H_
using Utility::String;
#endif
..
#ifdef UTILITY_SOMETHING_ELSE_H
using Utility::SomethingElse;
#endif
..
What do you think?
That way you could retain the "expected" behavior in your library .h but also have your the way you like. You also get to keep the benefit of the namespace over your classes (at the expense of having to maintain your new .h file).