Is the scope of the pre-compiler define the file where it defined?
for example:
three files :
test1.hpp/test1.cpp
test2.hpp/test2.cpp
test3.hpp/test3.cpp
An within test1.cpp:
#ifndef test1_hpp
#define test1_hpp
// some declarations
#endif
test2.hpp and test.hpp both #include test1.hpp. If the scope of test1_hpp is the whole application, as far as I understand, there can only one include test1.hpp success. Because once included, test1_hpp is defined.
test2.hpp and test.hpp both #include test1.hpp. If the scope of test1_hpp is the whole application, as far as I understand, there can only one include test1.hpp success. Because once included, test1_hpp is defined.
The compiler works on translation units (think: individual .cpp files) not the whole application (think: executable). What you call "the scope of the pre-compiler define" is the current translation unit. In your example, the // some declarations part in test1.hpp would be visible/processed in each of the CPPs that include test1.hpp directly or indirectly i.e. in all of test1.cpp (directly), test2.cpp, test3.cpp (indirectly, via both #include test1.hpp).
The #ifndef test1_hpp is a common idiom to prevent inadvertent inclusion of the same header file multiple times within the same translation unit - see for example "Use of #include guards" on Wikipedia.
Your assumption is correct. If you use the #ifndef guard in your header, the first time that test1.hpp is included in your application by the pre-processor, test1_hpp will be defined and will allow the inclusion of the code in your header. In future includes of test1.hpp, the code won't be re-included thanks to the guard.
This is needed, in most part, to prevent double definitions upon including the header in multiple files of your project, and comply with the one definition rule.
Related
I have a header file "USpecs.h":
#ifndef USPECS_H
#define USPECS_H
#include "Specs.h"
#include <iostream>
#include <vector>
std::vector<Specs*> UcakSpecs;
#endif
I am using this header both in main function and another class named Ucak.
But when i build it the following error occurs:
Ucak.cpp|6|multiple definition of `UcakSpecs'|
As i searched before, it should be okay with #ifndef but it is not.
The include guards only prevent multiple definitions within a single translation unit (i.e. a single source file with its included headers). They do not prevent multiple definitions when you include the header from multiple source files.
Instead, you should have a declaration in the header:
extern std::vector<Specs*> UcakSpecs;
and a definition in one (and only one) source file:
std::vector<Specs*> UcakSpecs;
Inclusion guards only prevent the header from being included in the same translation unit more than once. If you include this header in multiple translation units, you will have multiple definitions of UcakSpecs across the program.
The way to declare a global variable is to declare it as extern in the header file:
#ifndef USPECS_H
#define USPECS_H
#inclde "Specs.h"
#include <iostream>
#include <vector>
extern std::vector<Specs*> UcakSpecs;
#endif
A global variable declared as extern is only a declaration.
Then make sure it is only defined in a single translation unit by defining it in an implementation file (perhaps in USpecs.cpp);
std::vector<Specs*> UcakSpecs;
The #ifndef only applies to a single compilation unit. Since you have two (the main function and Ucak class), the variable is defined twice.
Consider declaring the variable as extern in the header file:
extern std::vector<Specs*> UcakSpecs;
and defining it inside the Ucak.cpp file:
std::vector<Specs*> UcakSpecs;
This should work.
I am refactoring some existing software and I regularly see this
#define XYZ
#include "stdafx.h"
where stdafx is the precompiled header file.
Q1. Can a knowledgeable person please confirm the following?
That (except perhaps for the file stdafx.cpp) the correct order is always
#include "stdafx.h"
#define XYZ
My reasoning is as follows. A define before the precompiled header can't affect the precompiled header even if 'used' inside the header, since the header is precompiled. The precompiled header will have used whatever the macro XYZ was set to when the initial compilation took place.
So
#define XYZ
#include "stdafx.h"
misleads a reader into thinking XYZ may have an influence on the contents of stdafx.h.
Q2. Whether the two are functionally equivalent and my refactoring is safe?
#include "stdafx.h"
#define XYZ
clearly defines XYZ whereas the alternative does not so clearly define it. (Using the precompiled header might well overwrite the definition with some compilers, for all I know.) Yet defining XYZ before including the precompiled header does seem to work, as it is present so often in the code I am refactoring.
Q3. Is the behaviour defined in a standard?
If I were the compiler writer, I would reject any #define prior to inclusion of a precompiled header! My VS2019 doesn't.
You state:
A define before the precompiled header can't affect the precompiled header even if 'used' inside the header, since the header is precompiled.
But from the Microsoft documentation Precompiled Header Files:
[#defines] Must be the same between the compilation that created the precompiled header and the current compilation. The state of defined constants is not checked, but unpredictable results can occur if your files depend on the values of the changed constants.
I am getting the error "method already defined in class.obj" on ALL my methods,
I've seen that some of the solutions include separating the class into a header and a .cpp file but it's not possible in this case.
Any help will be much appreciated.
this is my h file: http://pastebin.com/k46JEQBH
the cpp has:
#include "stdafx.h"
#include "poly.h"
The problem is your definitions are in your header, and it's probably being included in multiple .cpp files. Each .cpp file is a new translation unit. Imagine you compile each .cpp file one at a time. For each .cpp file that includes your header, it will be the first time that header is encountered, POLY_H will not have been defined yet. Declarations are allowed to appear multiple times, but definitions are not. Move your definitions to a separate .cpp file and everything should work.
Edit: Keeping the definition in your header is necessary and allowed for template classes, but your class is not templated.
Could it be your usage of #pragma once? What compiler are you using?
And have you tried using include guards instead to see if that resolves the errors? For example:
#ifndef POLY_H
#define POLY_H
//your code minus the pragma once
#endif //POLY_H
I am getting error messages from the mbed C++ compiler that seem to be indicative of malfunctioning include guards.
In main.cpp, I include my header file as follows:
#include "mbed.h"
#include "sample.h"
This is my sample.h:
#include "mbed.h"
#ifndef STUFF_H
#define STUFF_H
/* LEDs */
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
/* Subroutines */
void sweepLEDs();
void pulseLEDs(int numPulses);
void clearLEDs();
#endif
In sample.cpp, I am including sample.h as follows:
#include "sample.h"
In both main.cpp and sample.cpp, I am referring to variables led1, led2, led3, led4 without declaring them. However, the compiler is outputting these complaints:
" Symbol led1 multiply defined (by sample.cpp.cpp.LPC1768.o and main.cpp.cpp.LPC1768.o)."
...
" Symbol led4 multiply defined (by sample.cpp.cpp.LPC1768.o and main.cpp.cpp.LPC1768.o)."
Are my include guards written improperly? Or is there some other issue?
(For reference, here is the link to the mbed.h source)
The issue is a misunderstanding of what include guards do. Include guards prevent the compiler from seeing the same content again in the same translation unit (for the same .cpp file). They do not prevent separate translation units from seeing the same code.
In your header file, you define (not just declare) the variables. Therefore every translation unit which includes the header creates its own copy of those variables.
The correct way to do it is to define the variables in a .cpp file and only declare them in the header (the include guards should be there anyway, to prevent multiple inclusion in the same translation unit).
That is, in your file sample.h, prefix your variables with extern and remove the initializer (so they are only declared, not defined), and define them in the corresponding .cpp file (the one where also the functions are defined), by putting the exact definitions from your header there.
In an unrelated note, you should put the #include "mbed.h" in sample.h inside the include guards, because some compilers optimize compile speed for such guards, and that optimization doesn't work if there's material outside the include guards. Note that this is not really a correctness issue (assuming mbed.h is properly protected by include guards as well), but a compiling performance issue.
You need to mark the declarations as "extern" like this:
extern DigitalOut led1;
Then define them (i.e. allocate storage for them) in sample.cpp by using the expression you used to have in the header.
This is a rather basic question, but it's one that's bugged me for awhile.
My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.
I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.
Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place? What is the best practice?
For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.
Some best practices:
Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers
Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers
Every header is wrapped with:
#ifndef HEADER_XXX_INCLUDED
#define HEADER_XXX_INCLUDED
...
#endif /* HEADER_XXX_INCLUDED */
Headers do not include each others in cycles
Often: there is a single "project-wide header file" like "config.h" or ".h" which is always included first by any .cpp or .C file. Typically this has platform related configuration data, project-wide constants and macros etc.
These are not necessarily "best practice", but rules which I usually follow also:
Project-specific headers are included as #include "..." and before the system-wide headers, which are included as #include <...>
Project-specific headers are included in alphabetical order as a way to ensure that there is no accidental, hidden requirement on which order they are included. As every header should include its dependents and the headers should be protected against multiple inclusion, you should be able to include them in any order you wish.
Check out John Lakos's Large-Scale C++ Software Design. Here's what I follow (written as an example):
Interface
// foo.h
// 1) standard include guards. DO NOT prefix with underscores.
#ifndef PROJECT_FOO_H
#define PROJECT_FOO_H
// 2) include all dependencies necessary for compilation
#include <vector>
// 3) prefer forward declaration to #include
class Bar;
class Baz;
#include <iosfwd> // this STL way to forward-declare istream, ostream
class Foo { ... };
#endif
Implementation
// foo.cxx
// 1) precompiled header, if your build environment supports it
#include "stdafx.h"
// 2) always include your own header file first
#include "foo.h"
// 3) include other project-local dependencies
#include "bar.h"
#include "baz.h"
// 4) include third-party dependencies
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
Precompiled Header
// stdafx.h
// 1) make this easy to disable, for testing
#ifdef USE_PCH
// 2) include all third-party dendencies. Do not reference any project-local headers.
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iosfwd>
#include <iostream>
#include <vector>
#endif
I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.
Bar.h:
class Foo;
class Bar
{
Foo * m_foo;
};
Bar.cpp:
#include "Foo.h"
#include "Bar.h"
Use only the minimum amount of includes needed. Useless including slows down compiling.
Also, you don't have to include a header if you just need to pointer to a class. In this case you can just use a forward declaration like:
class BogoFactory;
edit: Just to make it clear. When I said minimum amount, I didn't mean building include chains like:
a.h
#include "b.h"
b.h
#include "c.h"
If a.h needs c.h, it needs to be included in a.h of course to prevent maintenance problems.
There are several problems with the #include model used in C/C++, the main one being that it doesn't express the actual dependency graph. Instead it just concatenates a bunch of definitions in a certain order, often resulting in definitions coming in a different order in each source file.
In general, the include file hierarchy of your software is something you need to know in the same way as you know your datastructures; you have to know which files are included from where. Read your source code, know which files are high up in the hierarchy so you can avoid accidentally adding an include so that it will be included "from everywhere". Think hard when you add a new include: do I really need to include this here? What other files will be drawn in when I do this?
Two conventions (apart from those already mentioned) which can help out:
One class == one source file + one header file, consistently named. Class A goes in A.cpp and A.h. Code templates and snippets are good here to reduce the amount of typing needed to declare each class in a separate file.
Use the Impl-pattern to avoid exposing internal members in a header file. The impl pattern means putting all internal members in a struct defined in the .cpp file, and just have a private pointer with a forward declaration in the class. This means that the header file will only need to include those headerfiles needed for its public interface, and any definitions needed for its internal members will be kept out of the headerfile.
Building on what antti.huima said:
Let's say you have classes A, B, and C. A depends on (includes) B, and both A and B depend on C. One day you discover you no longer need to include C in A, because B does it for you, and so you remove that #include statement.
Now what happens if at some point in the future you update B to no longer use C? All of a sudden A is broken for no good reason.
In A.cpp, always include A.h first, to ensure that A.h has no additional dependencies.
Include all local (same module) files before all project files before all system files, again to ensure that nothing depends on pre-included system files.
Use forward declarations as much as possible.
Use #indef/#define/#endif pattern
If a header is included in A.h, you don't need to include it in A.cpp. Any other headers A.cpp needs must be explicitly included, even if they happen to be provided by other .h files.
Organizing code files in C and C++: