#define XYZ before #include precompiled header - c++

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.

Related

Have C++ standard library ifdef or ifndef preprocessor instructions?

I'm building my own terminal app project in C++ and I'm asking myself if standard library has ifdef or ifndef preprocessors instructions. I want to know that because I need to create different header files which need some standard library headers such as "string" and some others, i don't want to include the same library 3 or more times because it makes the program heavier.
For example i wrote on my header files something like this to prevent the .h file to be included more than once:
#ifndef myheader_h
#define myheader_h
// my file code here
#endif
I tried compiling but the compiler say me nothing about errors or warnings.
I also tried to read the standard-library source code (https://en.cppreference.com/w/cpp/header) and I haven't found any preprocessor rule like ifdef or ifndef.
Should i include standard library headers like this?
#ifndef string_h
#define string_h
#include <string>
#endif
I hope my question isn't already asked because I haven't found it while searching it.
Updates
To some who said "you're not in the position where you need to worry about" and who said "it costs very little if it has proper include guards", I meant: program's heaviness is important, I want to make it slighter so I don't want to entirely include the same file multiple times. Have std lib files proper include guards? (my header files have them, didn't know std lib files)
There is no requirement for the standard header files to #define any specific pre-processor symbols to make sure they can be #included multiple times.
Having said that, any sane implementation would make sure that they can be #included multiple times without adversely affecting application code.
Turns out, that is a requirement by the standard for most headers (Thanks, #Rakete1111).
From the C++ standard
A translation unit may include library headers in any order ([lex]). Each may be included more than once, with no effect different from being included exactly once, except that the effect of including either <cassert> or <assert.h> depends each time on the lexically current definition of NDEBUG.
Not only that, they are very likely to be using the #pragma once directive. Hence, even if you use #include multiple times for the same header, they are going to be read only once.
In summary, don't worry about standard header files. If your header files are implemented correctly, your application would be just fine.
Those preprocessor directives you're talking about are called "header guards", and the standard library headers definitely have them (or some other mechanism that does the same thing) like all other proper header files. Including them multiple times shouldn't cause any problems, and you only need to worry about these when you're writing your own header files.
The "source code" that you're reading is just the documentation which says how the header files should work, but it doesn't provide the actual code. To see the code, you can look in the header files provided by your compiler. For example, the <iostream> header in Visual Studio has both #pragma once and header guards:
#pragma once
#ifndef _IOSTREAM_
#define _IOSTREAM_
//...
#endif /* _IOSTREAM_ */
The headers provided by the GCC compiler also has header guards:
#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1
//...
#endif /* _GLIBCXX_IOSTREAM */
I'm asking myself [sic] if standard library has ifdef or ifndef preprocessors instructions
The standard doesn't specify whether there are ifdef-style header guards, although it does require that multiple inclusion is protected in some manner. I took a look at a random header of stdlibc++ standard library implementation. It does have header guards.
i don't want to include the same library 3 or more times because it makes the program heavier
Including a header file multiple times does not make a program "heavier".
Should i include standard library headers like this?
#ifndef string_h
#define string_h
#include <string>
#endif
That is not necessary, or particularly useful.

Why doesn't the compiler automatically add or generate an include guard by default?

I know C or C++ code usually needs to use include guards like this:
#ifndef __A__H__
#define __A__H__
class A{
};
#endif
and to speed up compile time, in other cpp (e.g.:B.cpp), it can change
#include "A.h"
to:
#ifndef __A__H__
#include "A.h"
#endif
but the question is why doesn't the compiler automatically add or generate the include guard, and therefore why does the programmer need to add it manually if an include guard is usually required?
There are times when it is absolutely incorrect to generate the header guard. The standards contain an example: <assert.h> in C and <cassert> in C++.
The effect of reincluding those headers depends on the state of the NDEBUG macro when the header is (re)included. It is legitimate to write:
#undef NDEBUG
#include <assert.h>
…code using assert…
#define NDEBUG 1
#include <assert.h>
…more code using assert…
If the compiler automatically generated a header guard, that would not work correctly. Therefore, compilers do not generate header guards automatically.
Incidentally, user code should not use header guard macro names that start with double underscore, or underscore capital letter. Such names are reserved for the implementation. In C++, no user-defined name may legitimately contain a double underscore at all. Use something more like:
#ifndef A_H_INCLUDED
#define A_H_INCLUDED
…body of header…
#endif
The compiler, or more strictly the pre-processor cannot determine the programmer's intent in using inclusion. The compiler does not explicitly distinguish between .h files and .c or .cpp files; they differ only in the type of code one places in them. In fact the compiler deals only in a single translation unit; it is the responsibility of the C preprocessor to concatenate all included files into a single file for compilation. It would be incorrect for the pre-processor to omit an inclusion that it has previously included because it has no semantic knowledge of the code and may cause intended behaviour to change by second-guessing the developer.
In some circumstances, an IDE may add include guards for template code that it has generated. For example Microsoft Visual Studio will add them for code that it generates via its project start-up wizards. If it happens at all, it is properly the responsibility of the IDE rather than the compiler or pre-processor.

Comprehension issue: Precompiled headers & include usage

I got a comprehension issue about precompiled headers, and the usage of the #include directive.
So I got my "stdafx.h" here and include there for example vector, iostream and string. The associated "stdafx.cpp" only includes the "stdafx.h", that's clear.
So if I design my own header file that uses for example "code" that's in vector or iostream, I have to include the header file because the compiler doesn't know the declarations at that time. So why are some posts here (include stdafx.h in header or source file?) saying, it's not good to include the "stdafx.h" in other header files even if this file includes the needed declarations of e.g. vectors? So basically it wouldn't matter to include directly a vector or the precompiled header file, both do the same thing.
I know of course, that I don't have to include a header file in another header file if the associated source file includes the needed header file, because the declarations are known at that time. Well, that only works if the header file is included somewhere.
So my question is: Should I avoid including the precompiled header file in any source file and why? And I am a bit confused, because I'm reading contradictory expressions on the web that I shouldn't include anything in header files anyway, or is it O.K. to include in header files?
So what's right now?
This will be a bit of a blanket statement with intent. The typical setup for PCH in a Visual Studio project follows this general design, and is worth reviewing. That said:
Design your header files as if there is no PCH master-header.
Never build include-order dependencies in your headers that you expect the including source files will fulfill prior to your headers.
The PCH master-header notwithstanding (I'll get to that in a moment), always include your custom headers before standard headers in your source files. This makes your custom header is more likely to be properly defined and not reliant on the including source file's previous inclusion of some standard header file.
Always set up appropriate include guards or pragmas to avoid multiple inclusion. They're critical for this to work correctly.
The PCH master-header is not to be included in your header files. When designing your headers, do so with the intent that everything needed (and only that which is needed) by the header to compile is included. If an including source file needs additional includes for its implementation, it can pull them in as needed after your header.
The following is an example of how I would setup a project that uses multiple standard headers in both the .h and .cpp files.
myobject.h
#ifndef MYAPP_MYOBJECT_H
#define MYAPP_MYOBJECT_H
// we're using std::map and std::string here, so..
#include <map>
#include <string>
class MyObject
{
// some code
private:
std::map<std::string, unsigned int> mymap;
};
#endif
Note the above header should compile in whatever .cpp it is included, with or without PCH being used. On to the source file...
myobject.cpp
// apart from myobject.h, we also need some other standard stuff...
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note myobject.h does not expect you to include something it relies on. It isn't using <iostream> or <algorithm>, etc. in the header; we're using it here.
That is a typical setup with no PCH. Now we add the PCH master
Adding the PCH Master Header
So how do we set up the PCH master-header to turbo-charge this thing? For the sake of this answer, I'm only dealing with pulling in standard headers and 3rd-party library headers that will not undergo change with the project development. You're not going to be editing <map> or <iostream> (and if you are, get your head examined). Anyway...
See this answer for how a PCH is typically configured in Visual Studio. It shows how one file (usually stdafx.cpp) is responsible for generating the PCH, the rest of your source files then use said-PCH by including stdafx.h.
Decide what goes in the PCH. As a general rule, that is how your PCH should be configured. Put non-volatile stuff in there, and leave the rest for the regular source includes. We're using a number of system headers, and those are going to be our choices for our PCH master.
Ensure each source file participating in the PCH turbo-mode is including the PCH master-header first, as described in the linked answer from (1).
So, first, the PCH master header:
stdafx.h
#ifndef MYAPP_STDAFX_H
#define MYAPP_STDAFX_H
// MS has other stuff here. keep what is needed
#include <algorithm>
#include <numeric>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#endif
Finally, the source files configured to use this then do this. The minimal change needed is:
UPDATED: myobject.cpp
#include "stdafx.h" // <=== only addition
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note I said minimal. In reality, none of those standard headers need appear in the .cpp anymore, as the PCH master is pulling them in. In other words, you can do this:
UPDATED: myobject.cpp
#include "stdafx.h"
#include "myobject.h"
// code, etc...
Whether you choose to or not is up to you. I prefer to keep them. Yes, it can lengthen the preprocessor phase for the source file as it pulls in the headers, runs into the include-guards, and throws everything away until the final #endif. If your platform supports #pragma once (and VS does) that becomes a near no-op.
But make no mistake: The most important part of all of this is the header myobject.h was not changed at all, and does not include, or know about, the PCH master header. It shouldn't have to, and should not be built so it has to.
Precompiled headers are a method to shorten the build time. The idea is that the compiler could "precompile" declarations and definitions in the header and not have to parse them again.
With the speed of todays computers, the precompilation is only significant for huge projects. These are projects with a minimum of over 50k lines of code. The definition of "signification" is usually tens of minutes to build.
There are many issues surrounding Microsoft's stdafx.h. In my experience, the effort and time spent with discovering and resolving the issues, makes this feature more of a hassle for smaller project sizes. I have my build set up so most of the time, I am compiling only a few files; the files that don't change are not compiled. Thus, I don't see any huge impact or benefit to the precompiled header.
When using the precompiled header feature, every .cpp file must begin by including the stdafx.h header. If it does not, a compiler error results. So there is no point in putting the include in some header file. That header file cannot be included unless the stdafx.h has already been included first.

Why Placing #include BEFORE include guards

Is there any valid reason for placing #include directives BEFORE the include guards in a header file like this:
#include "jsarray.h"
#include "jsanalyze.h"
#include "jscompartment.h"
#include "jsgcmark.h"
#include "jsinfer.h"
#include "jsprf.h"
#include "vm/GlobalObject.h"
#include "vm/Stack-inl.h"
#ifndef jsinferinlines_h___
#define jsinferinlines_h___
//main body mostly inline functions
#endif
Note, this example is a taken from a real life high profile open source project that should be developed by seasoned programmers - the Mozilla Spidermonkey open source Javascript engine used in Firefox 10 (the same header file also exists in the latest version).
In high profile projects, I expect there must be some valid reasons behind their design. What are the valid reasons to have #include before the include guard? Is it a pattern applicable to inline-function-only header files? Also note that this header file (jsinferinlines.h) is actually including itself through the last #include "vm/Stack-inl.h" (this header file includes a lot of other headers and one of them actually includes this jsinferinlines.h again) directive before the include guard, this makes even less sense to me.
Because you expect those headers to have include guards of their own, therefore it doesn't really make any difference.
Also note that this header file (jsinferinlines.h) is actually including itself through the last #include "vm/Stack-inl.h" (this header file includes a lot of other headers and one of them actually includes this jsinferinlines.h again) directive before the include guard, this makes even less sense to me.
It won't make any different because the workflow, when including that file, will be:
include all header up to "vm/Stack-inl.h"
include the "vm/Stack-inl.h" up to the last #include "jsinferinlines.h" (your file)
include the file jsinferinlines.h again (skipping all the previous includes, because include guards)
reach past #include "vm/Stack-inl.h"
finally process from #ifndef jsinferinlines_h___ on
But in general, mutual header recursion is bad and should be avoided at all costs.
There were lots of include cycles in SpiderMonkey headers back then, and placing the header guard at the top caused difficult to understand compile errors - I suspect that putting the header guard below the includes was just an incremental step toward sanitizing the includes.
I couldn't tell you the exact sequence of includes that caused it to make a difference, though.
Nowadays there shouldn't be any include cycles in SM headers, and their style is enforced through a python script written by Nicholas Nethercote. If you look at jsinferinlines.h today you'll see the header guard is at the top where it belongs.

should I include a header that is already included via other headers?

I had only just noticed my programs using the string class were compiling without including the <string> header. It turns out that <iostream> includes <ios_base> which in turn includes <string>.
Is this bad practice and should I explicitly include <string>? Even if it's just a case of clarity?
Is it safe to assume this applies to more than just the <string> header? Perhaps this is implementation specific and or does the standard state the <string> header be included via <ios_base> and <iostream>? Ensuring that any respected and widely used implementation will always include <string> providing the the call to <iostream> exists.
You should explicitly include whatever standard library headers you need.
It is not specified which standard library headers are included by other standard library headers, so such details will differ between compilers.
One case where you can rely on a header being included by another header is if a class in one header derives from a class in another. For example, <iostream> has to include <ios_base> because classes defined in <iostream> are derived from classes defined in <ios_base>.
A good practice is to always include the headers for the classes you'll be using in a given source file, regardless of whether you "know" they're included by already-included files.
If, while refactoring your code, you remove the necessity for one of the higher-level included files (iostream, for example), it could become quite painful to determine why your application no longer compiles.
If you add a proper header (with '#pragma once' or the proper #ifndef) more than once, it only adds a little more time to compiling (just to open, parse and through away the header file contents), but nothing too serious while it makes your files more easy to compile, should the circumstances change (i.e. move them to a different project, make a library out of them, e.t.c.)
If you are really concerned about compile time add the same #ifndef before including the header (though I don't recommend it)
i.e.
// header.h
#ifndef _HEADER_H
#define _HEADER_H
int blahblahblah(int);
#endif
// cppfile.cpp
#ifndef _HEADER_H
#include <header.h>
#endif