I have two libraries in my include path:
/usr/local/include/lib1/
/user/include/lib2/
Both define a header file "vec.h" and I get the following error:
/usr/local/include/lib1/vec.h:22: error: redeclared with...
How to handle this?
You do:
#include "lib1/vec.h"
#include "lib2/vec.h"
Your makefile should then have include paths up to the lib1 and lib2.
-I /usr/local/include /user/include
You should ensure that the headers have guards around them to make sure they don't get declared twice. You should see something like:
#ifndef MYHEADER_H_ab2592zx1__
#define MYHEADER_H_ab2592zx1__
#include ...
#include ...
class ...
#endif
You should have these guards regardless of whether you have two includes of the same name and they should typically end with something fairly random in order to limit/lower the possibility that they conflict with a header guard in another file.
(Sorry, can't comment yet, so posting as an answer.) What exactly is at line 22 of lib1/vec.h and what is the complete error message? It looks like the header is trying to declare something that was already declared in a different way somewhere, which may even have nothing to do with lib2/vec.h.
EDIT
So you have a name clash. I don't know what library trimesh2/include/Vec.h belongs to (probably lib2), but the problem is definitely a conflict between this header and lib1/img.h. Two libraries define two different classes with the same name Vec. There is no solution to this problem unless you have sources of one of the libraries and are willing to rename one of Vecs to something else and recompile it. You just can't have two different things with the same name in one program.
Related
As I have worked on my program, I have gotten to a point where I have about 30+ header files.
When I started, I had an all-in-one header that linked to all the header files I made up to date, as well as the libraries I needed for the project.
With this format, I had to take 5+ minutes in order to recompile the ENTIRE program as a whole just by changing a variable name or something equally as small.
My previous plan was to make a "Tier List" of all my headers, where the most basic ones are at the bottom, the next level headers required these, so on and so forth until I got to the main.cpp file. (Tier 2 needed the highest of Tier 1 and so on). After this idea, I eventually deviated into making folder groups, and having a Folder.hpp file for if I needed everything in that directory.
Now when compiling, I am immediately overwhelmed with syntax errors saying that nothing is properly included, when the include command is sitting right in front of my face.
Here are some of the headers, as per one of the syntax errors:
===Character.hpp===
#include "../../Pre.hpp"
#include "../Assets/Folder.hpp"
#include "../Control/Folder.hpp"
#include "../WorldObj.hpp"
===Control/Folder.hpp===
#include "CommonStat.hpp"
#include "DeathHandler.hpp"
#include "EnergySys.hpp"
#include "FactionHandler.hpp"
#include "Interaction.hpp"
#include "Warper.hpp"
#include "WeaponPos.hpp"
===WeaponPos.hpp===
struct WeaponPos{};
===Build Message===
Build Message: error: 'WeaponPos' does not name a type
===NOTE===
The #include lines are the only (seemingly) important portions of the code. the 'struct WeaponPos' is only to show where it is located in terms of the syntax error.
WeaponPos myWpnPos is a variable of Character Forgot to inlcude that note.
What would be a good way to properly and effectively organize the header files so they are all accountable when compiling a source file?
I am using Code::Blocks and MinGW GCC 4.7 on Windows 7 64-bit.
This by no means solves your entire problem, but it is worth knowing that it exists and it may actually help in your future design decisions.
One of the ways of handling long time to recompile caused by a small change is PIMPL idion - general idea is to have a separate struct with all private members of the class. The struct is forward declared in header file and defined in cpp file of the class. Therefore, when you add/rename a field in your private struct, header doesn't change at all, thus other headers linking to it don't have to be recompiled.
Much better description with examples
Another important point is not to create levels of included headers - one should rather include headers only if they are really needed. Good example of this is forward declaration. If you have Class1 as a pointer-member in Class2, you don't have to actually include Class1.h in Class2.h - it is usually enough to forward declare Class1 and then include the header in the Class2.cpp file - which reduces recompilation greatly.
To sum up:
use PIMPL
forward declare and include in cpp when you can
do not include when you don't have to
I was wondering if there is some pro and contra having include statements directly in the include files as opposed to have them in the source file.
Personally I like to have my includes "clean" so, when I include them in some c/cpp file I don't have to hunt down every possible header required because the include file doesn't take care of it itself. On the other hand, if I have the includes in the include files compile time might get bigger, because even with the include guards, the files have to be parsed first. Is this just a matter of taste, or are there any pros/cons over the other?
What I mean is:
sample.h
#ifdef ...
#include "my_needed_file.h"
#include ...
class myclass
{
}
#endif
sample.c
#include "sample.h"
my code goes here
Versus:
sample.h
#ifdef ...
class myclass
{
}
#endif
sample.c
#include "my_needed_file.h"
#include ...
#include "sample.h"
my code goes here
There's not really any standard best-practice, but for most accounts, you should include what you really need in the header, and forward-declare what you can.
If an implementation file needs something not required by the header explicitly, then that implementation file should include it itself.
The language makes no requirements, but the almost universally
accepted coding rule is that all headers must be self
sufficient; a source file which consists of a single statement
including the include should compile without errors. The usual
way of verifying this is for the implementation file to include
its header before anything else.
And the compiler only has to read each include once. If it
can determine with certainty that it has already read the file,
and on reading it, it detects the include guard pattern, it has
no need to reread the file; it just checks if the controling
preprocessor token is (still) defined. (There are
configurations where it is impossible for the compiler to detect
whether the included file is the same as an earlier included
file. In which case, it does have to read the file again, and
reparse it. Such cases are fairly rare, however.)
A header file is supposed to be treated like an API. Let us say you are writing a library for a client, you will provide them a header file for including in their code, and a compiled binary library for linking.
In such scenario, adding a '#include' directive in your header file will create a lot of problems for your client as well as you, because now you will have to provide unnecessary header files just to get stuff compiling. Forward declaring as much as possible enables cleaner API. It also enables your client to implement their own functions over your header if they want.
If you are sure that your header is never going to be used outside your current project, then either way is not a problem. Compilation time is also not a problem if you are using include guards, which you should have been using anyway.
Having more (unwanted) includes in headers means having more number of (unwanted) symbols visible at the interface level. This may create a hell lot of havocs, might lead to symbol collisions and bloated interface
On the other hand, if I have the includes in the include files compile time might get bigger, because even with the include guards
If your compiler doesn't remember which files have include guards and avoid re-opening and re-tokenising the file then get a better compiler. Most modern compilers have been doing this for many years, so there's no cost to including the same file multiple times (as long as it has include guards). See e.g. http://gcc.gnu.org/onlinedocs/cpp/Once_002dOnly-Headers.html
Headers should be self-sufficient and include/declare what they need. Expecting users of your header to include its dependencies is bad practice and a great way to make users hate you.
If my_needed_file.h is needed before sample.h (because sample.h requires declarations/definitions from it) then it should be included in sample.h, no question. If it's not needed in sample.h and only needed in sample.c then only include it there, and my preference is to include it after sample.h, that way if sample.h is missing any headers it needs then you'll know about it sooner:
// sample.c
#include "sample.h"
#include "my_needed_file.h"
#include ...
#include <std_header>
// ...
If you use this #include order then it forces you to make sample.h self-sufficient, which ensures you don't cause problems and annoyances for other users of the header.
I think second approach is a better one just because of following reason.
when you have a function template in your header file.
class myclass
{
template<class T>
void method(T& a)
{
...
}
}
And you don't want to use it in the source file for myclass.cxx. But you want to use it in xyz.cxx, if you go with your first approach then you will end up in including all files that are required for myclass.cxx, which is of no use for xyz.cxx.
That is all what I think of now the difference. So I would say one should go with second approach as it makes your code each to maintain in future.
I started writing a simple interpreter in C++ with a class structure that I will describe below, but I quit and rewrote the thing in Java because headers were giving me a hard time. Here's the basic structure that is apparently not allowed in C++:
main.cpp contains the main function and includes a header for a class we can call printer.h (whose single void method is implemented in printer.cpp). Now imagine two other classes which are identical. Both want to call Printer::write_something();, so I included printer.h in each. So here's my first question: Why can I #include <iostream> a million times, even one after the other, but I can only include my header once? (Well, I think I could probably do the same thing with mine, as long as it's in the same file. But I may be wrong.) I understand the difference between a declaration and an implementation/definition, but that code gives me a class redefinition error. I don't see why. And here's the thing that blows my mind (and probably shows you why I don't understand any of this): I can't just include printer.h at the top of main.cpp and use the class from my other two classes. I know I can include printer.h in one of the two classes (headers) with no trouble, but I don't see why this is any different than just including it before I include the class in main.cpp (as doing so gives me a class not found error).
When I got fed up, I thought about moving to C since the OOP I was using was quite forced anyway, but I would run into the same problem unless I wrote everything in one file. It's frustrating to know C++ but be unable to use it correctly because of compilation issues.
I would really appreciate it if you could clear this up for me. Thanks!
Why can I #include a million times, even one after the other, but I can only include my header once?
It is probably because your header doesn't have an include guard.
// printer.h file
#ifndef PRINTER_H_
#define PRINTER_H_
// printer.h code goes here
#endif
Note that it is best practice to chose longer names for the include guard defines, to minimise the chance that two different headers might have the same one.
Most header files should be wrapped in an include guard:
#ifndef MY_UNIQUE_INCLUDE_NAME_H
#define MY_UNIQUE_INCLUDE_NAME_H
// All content here.
#endif
This way, the compiler will only see the header's contents once per translation unit.
C/C++ compilation is divided in compilation/translation units to generate object files. (.o, .obj)
see here the definition of translation unit
An #include directive in a C/C++ file results in the direct equivalent of a simple recursive copy-paste in the same file. You can try it as an experiment.
So if the same translation unit includes the same header twice the compiler sees that some entities are being defined multiple times, as it would happen if you write them in the same file. The error output would be exactly the same.
There is no built-in protection in the language that prevents you to do multiple inclusions, so you have to resort to write the include guard or specific #pragma boilerplate for each C/C++ header.
I have two versions of a same class in two different files (A.cpp, A.h, B.cpp, B.h) in all files the class has the same name but different internal implementation.
My idea is to switch from one version to the other just by changing the name of the .h file at #include, so I shouldn't have to change anything else in the code (both version's methods have the same signature and same properties)
The A.h and B.h are never included at the same time.
The problem is that no matter what include file I use always A version is executed. I know that when I include B.h at least it is compiled (by putting some code error they are shown at compilation time)
Can this be done? or this is breaking some rules of C++? I think that this should not break One Definition Rule because I'm not using A.h and B.h at the same time.
The solution is not to link the old file into final executable. That way only the new implementation will be available.
What I'll often do is mangle the version into a namespace, and use that.
Something along the lines of:
namespace Xyz_A { // In A.h
// Define version A
}
namespace Xyz = Xyz_A;
; in B.h, use _B instead.
This way, you would write Xyz::... in your program, but the external
symbols will have Xyz_A or Xyz_B mangled into them. But in my
option, this is really more a protection against errors. I'll arrange
things in my makefiles so that whatever switches between A.h and B.h
also causes the executable to link against the appropriate library, and
not against the other.
If the header files are identical it would be easier just to have one header and 2 different implementations files. That would reduce your problem to just linking with the right object file. This also reduces the chance of subtle bugs should your headers ever diverge.
A better solution would, of course, something that does not depend on the build system but uses language facilities to change code at compile time, like a template.
You will need to load the correct library to match the header file.
I would suggest looking into the proxy design pattern so you can include both class A and B. Then you can use the proxy to choose which class function to use during runtime.
http://en.wikipedia.org/wiki/Proxy_pattern
In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, define it, which may be useful depending on what tool you are using to compile and link your project. However, I have two questions:
Is this fairly common? I don't see it too often. And is it a good idea to use that rubric, or should you just jump right into defining your code.
What is EXAMPLE_H_ exactly? Why not example.h, or just example? Is there anything special about that, or could is just be an artifact of how eclipse prefers to auto-build projects?
This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.
Putting the #ifndef wrapper around the contents means the compiler only parses the header's contents once, and avoids redefinition errors.
Some compilers allow "#pragma once" to do the same thing, but the #ifndef construct works everywhere.
This is just a common way to protect your includes - in this way it prevents the code from being included twice. And the identifier used could be anything, it's just convention to do it the way described.
Is it common? Yes - all C and C++ header files should be structured like this. EXAMPLE_H is a header guard, it prevents the code in the header being included more than once in the same translation unit, which would result in multiple definition errors. The name EXAPMLE_H is chosen to match the name of the header file it is guarding - it needs to be unique in your project and maybe globally as well. To try to ensure this, it's normal to prefix or suffix it with your project name:
#define MYPROJ_EXAMPLE_H
for example, if your project is called "myproj". Don't be tempted into thinking that prefixing with underscores will magically make it unique, by the way - names like _EXAMPLE_H_ and __EXAMPLE_H__ are illegal as they are reserved for the language implementation.
Always do this at the top of a header file. It's typically called a header guard or an include guard.
What it does is make it so that if a header file would be included multiple times, it will only be included once. If you don't do it, then you'll end up with errors about things being defined multiple times and things like that.
The exact define doesn't matter that much, though typically it's some variation on the file name. Basically, you're checking whether the given macro has been defined. If it hasn't, then define it, and continue with including the file. If it has, then you must have included the file previously, and the rest of the file is ignored.
This is an include guard. It guarantees that a header is included no more than once.
For example, if you were to:
#include "example.h"
#include "example.h"
The first time the header is included, EXAMPLE_H_ would not be defined and the if-block would be entered. EXAMPLE_H_ is then defined by the #define directive, and the contents of the header are evaluated.
The second time the header is included, EXAMPLE_H_ is already defined, so the if-block is not re-entered.
This is essential to help ensure that you do not violate the one definition rule. If you define a class in a header that didn't have include guards and included that header twice, you would get compilation errors due to violating the one definition rule (the class would be defined twice).
While the example above is trivial and you can easily see that you include example.h twice, frequently headers include other headers and it's not so obvious.
Consider this
File foo.c:
#include foo.h
#include bar.h
File bar.h
#include <iostream>
#include foo.h
Now, when we compile foo.c, we have foo.h in there twice! We definitely don't want this, because all the functions will throw compile errors the second time around.
To prevent this, we put the INCLUDE GUARD at the top. That way, if it's already been included, we define a preprocessor variable to tell us not to include it again.
It's very common (often mandated), and very frustrating if someone doesn't put one in there. You should be able to simply expect that each .h file has a header guard when you included. Of course, you know what they say when you assume things ("makes an ass of u and me") but that should be something you're expecting to see.
This is called an include guard and is indeed a common idiom for C/C++ header files. This allows the header file to be included multiple times without multiply including its contents.
The name EXAMPLE_H_ is an arbitrary convention but has to obey naming rules for C preprocessor macros, which excludes names like example.h. Since C macros are all defined in a single global namespace, it is important that you do not have different header files that use the same name for their include guard. Therefore, it is usually a good idea to include the name of your project or library in the include guard name:
#ifndef __MYPROJECT_EXAMPLE_H__
...