C++ preprocessor executing both #ifdef and #ifndef - c++

So I'm currently working on something that uses OpenCL. The OpenCL spec provides the users with a directive which must be included before the inclusion of the header (cl.h)
#define CL_TARGET_OPENCL_VERSION 110
Which basically defines the version they want to use. Suppose I'm making a library and I want my users to define this instead of me defining this inside my files. What I did was.
-----main.cpp---
#define CL_TARGET_OPENCL_VERSION 110
#include "library.h"
-------x---------
----library.h-----
#ifdef CL_TARGET_OPENCL_VERSION
#pragma message("def")
#endif
#ifndef CL_TARGET_OPENCL_VERSION
#pragma message("ndef")
#endif
.... include other headers.
--------x---------
And the compiler prints both def and ndef messages. And the OpenCL library also throws a warning that it's undefined. I thought that the library header would get substituted into main and it'd only print the def message. Is there anything I understood wrong?
I'm particularly confused as to where does the preprocessor start? If it starts from main.cpp and goes from top to down, then it surely has defined the macro. After that it sees the library inclusion, then it should only print the def message but it prints both.
This leds me to believe the preprocessor does scan the header file before including it in main? Dunno the reason why. Also I have assured that the library header isn't included elsewhere.
One interesting thing I noticed was, if i did this
-----helper.h---
#define CL_TARGET_OPENCL_VERSION 110
-------x---------
----library.h-----
#include helper.h
#ifdef CL_TARGET_OPENCL_VERSION
#pragma message("def")
#endif
#ifndef CL_TARGET_OPENCL_VERSION
#pragma message("ndef")
#endif
.... include other headers.
--------x---------
It prints the def message "twice". If anybody can explain all this I'd be grateful.
EDIT:- The files I'm compiling are main.cpp library.h and library.cpp
Library.cpp includes library.h from the start as usual. Maybe this other cpp is causing the problem?

In C/C++ programs, the compiler handles each .c and .cpp file separately.
The compilers build each source file (NOT the header files, only .c and .cpp files) independently from each other (this source files are called compilation unit).
Thus, when your main.cpp is built, the compiler finds the #define CL_TARGET_OPENCL_VERSION 110 you have added on top of the main.cpp file, emiting the defmessage.
But when the compiler builds the library.cpp file, it does not find the version define, so it emits the ndef message.
So, following this explanation, it is completely normal that in your last case, when you add the define to the .h file, the compiler emits the def message twice, once for the main.cpp file and once for the library.cpp file.
Now, the problem is where should you add the define, in order to have the program built consistently, with the same version for all the .cpp files.
Usually, all the IDEs have some configuration page where you can add global defines, for all the project, which are "inserted" into all the compilation units before everything else. So when the IDE calls the compiler, it passes the same defines to all the compilation units. You should add this kind of defines in this page.
In your IDE (I am using Code::Blocks, v 17.12), you can find this page in the menu: Project / Build Options
For each type (Debug or Release), you have to go to the tab Compiler Settings, and there to the sub tab #defines. There you can add global defines, which can be different if you are building in Debug or in Release mode (of course, if you set the same in both modes, they would be the same).
Once you have added your define here, please, remove it from the main.cpp, library.h and any other place where you may have added it, in order to avoid duplicities.
From the comments about portability:
You have several options:
Always use Code::Blocks: this would be the easiest way, since you can pass the Code::Blocks project along with the source files, and everything would be already setup.
Use cmake, which is a script build system, where you can set defines and so in the same way as using an IDE. cmake is much widely used than Code::Blocks, so maybe it is a better option.
Add a new options.h header file, where you set all the defines, and include it to all your .c/.cpp. This setup has the additional benefit that for different systems, changing only the options.h file the build can be completely different. This is a manually setup of what the IDE is doing. It has the advantage that does not rely on external tools, but the disadvantage that you have to remember to add it in all the new .cpp files added to the project.
My recommendation is go with cmake, just as the others have said.

Prefer using #ifndef XXXX_h #define XXXX_h #endif over #pragma once
If your #include search path is sufficiently complicated, the compiler may be unable to tell the difference between two headers with the same basename (e.g. a/foo.h and b/foo.h), so a #pragma once in one of them will suppress both. It may also be unable to tell that two different relative includes (e.g. #include "foo.h" and #include "../a/foo.h" refer to the same file, so #pragma once will fail to suppress a redundant include when it should have.
This also affects the compiler's ability to avoid rereading files with #ifndef guards, but that is just an optimization. With #ifndef guards, the compiler can safely read any file it isn't sure it has seen already; if it's wrong, it just has to do some extra work. As long as no two headers define the same guard macro, the code will compile as expected. And if two headers do define the same guard macro, the programmer can go in and change one of them.
#pragma once has no such safety net -- if the compiler is wrong about the identity of a header file, either way, the program will fail to compile. If you hit this bug, your only options are to stop using #pragma once, or to rename one of the headers. The names of headers are part of your API contract, so renaming is probably not an option.
(The short version of why this is problematic to use #pragma is that neither the Unix nor the Windows filesystem API offer any mechanism that guarantees to tell you whether two absolute pathnames refer to the same file.)

Related

Preventing multiple #define when including headers

coming from python and am a bit tripped up on what the proper approach to this is.
I am trying to include this library in my project:
https://github.com/nothings/stb/blob/master/stb_image.h
to do so, i have to #define STB_IMAGE_IMPLEMENTATION exactly once before importing the file (as per that file's doc)
This makes sense, where I am confused is, I have CLASS.h/cpp and in .h I define functions that use typedefs from that file, so I have
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
in that header file, and can't move these lines to .cpp as headers needs the defs for function def, but as soon as another file includes this header, (#ifndef wont help, i believe), that will be defined twice
I have a structure where TOP creates the CLASS above, but parent also creates OTHER, and OTHER needs to include PARENT, which includes CLASS, which triggers the issue (and prevents me from just moving the #define to PARENT) Note the actual class structure is more complex then this, but this idea seems to be a core issue, and I'm looking for the general best practice.
So, is there some way to ensure these #defines are defined before anything else, and done only once? This seems like a fundamental thing but I can't figure it out - What's the best approach?
This code is a library, and doesn't have a defined entry if that matters
Create a cpp file (or whatever extension you are using for your source files) whose sole purpose is to have
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
and don't forget to include this cpp file into your project so that it is compiled and the result is linked into your program. In all other places where you need something from this library, just include the stb_image.h header as usual.
These "implementation" macros are a "trick" used by some library authors to make "installing" their library easy. The idea is that when a specific macro (chosen by the library authors) is defined before the header of that library is included, some code with the actual implementation will be added. That is why this must be in a source file instead of a header and only in one source file (otherwise you get multiple definitions for the same functions).
You should have the #define STB_IMAGE_IMPLEMENTATION macro definition in exactly one source file that includes <stb_image.h> (a .cpp file, not in a header).
Since you can also only have one source file that defines main(), it is simple to put the #define in the same file as main() (as long as it also includes <stb_image.h>), but it can be used in any other source file if you prefer. You could even create a source file stb_image_imp.cpp that contains just the two lines shown, and link that into your program (or library) too.
All other source files in the project should only include <stb_image.h> without also defining the macro.
#define is a preprocessor directive and doesn't actually get run everytime the header is accessed so you should
't have any problems
if you are using visual studio you can also do #pragma once to only parse the file once stopping anything from happening twice

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.

When do i want to turn off "precompiled header" in visual studio?

First of all i want to say that I read about precompiled headers and I understand that this is an optimization that saves me the time of compiling headers over and over on every built.
I'm reading the documentation of boost and I see that in the instructions they say:
In Configuration Properties > C/C++ > Precompiled Headers, change Use Precompiled Header (/Yu) to Not Using Precompiled Headers
And then they explain it:
There's no problem using Boost with precompiled headers; these instructions merely avoid precompiled headers because it would require Visual Studio-specific changes to the source code used in the examples.
Can some explain me the sentence I marked in bold? which visual studio specific changes they are talking about ? (Here is the link to the documentation I'm reading: http://www.boost.org/doc/libs/1_55_0/more/getting_started/windows.html#pch)
Why and when I would want to turn off the precompiled headers?
what is the difference between "Create" and "Use" in the precompiled header options.
Originally a comment, but I may as well post it. Note: this is specific to VC++:
The bold sentence is their way of saying the samples don't follow the mantra of a unified use-this-lead-in-header-for-pch-generation model. IOW, their samples aren't PCH-friendly, but you can still use pch with boost in your projects if properly configured.
You would turn them off for a variety of reasons. Some source modules, particularly ones from 3rd-parties, don't follow the PCH model of including "the" pch-through-header at their outset. Their samples are such code (and thus the advise to turn them off for their samples). Sometimes source files require different preprocessor configurations only for this files and not all files int he project; another reason to disable PCH for those files.
You typically use a source/header pair to generate "the One"; the precompiled header image. This header file typically includes:
Any system standard lib headers used by your project
3rd-party SDK headers
Just about everything else that is NOT in active development for your project.
The single source file tagged as Create typically includes one line of code : #include "YourHeaderFile.h", where YourHeaderFile.h is the header you filled with stuff from the list above. Tagging it as "Create" through header YourHeaderFile.h tells VC it is the file needed for rebuilding the PCH through that header when compiling other source files. All other source files are tagged as Use (except the ones where PCH is turned off) and should include, as their first line of code, the same #include "TheHeaderFile.h".
In short (hard to believe), <boost> is telling you their samples aren't setup like described above, and as such you should turn PCH off when building them.
When you use pre-compiled headers, you need to do something like:
#include <foo>
#include <bar>
#include <baz>
#pragma hdrstop
// other code here
Everything before the #pragma goes into the precompiled header. Everything after it depends on the precompiled header. The VC++ specific "magic" to make pre-compiled header work is that #pragma.
There's a little more to the story than just that though. To make pre-compiled headers work well, you want to include exactly the same set of headers in exactly the same order in every source file.
That leads to (typically) creating one header that includes all the other common headers and has the #pragma hdrstop right at its end, then including that in all the other source files.
Then, when the compiler does its thing, there are two phases: first you need to create a pre-compiled header. This means running the compiler with one switch. The compiler only looks at what comes before the #pragma hdrstop, builds a symbol table (and such) and puts the data into a .pch file.
Then comes the phase when you do a build using the pre-compiled header. In this phase, the compiler simply ignores everything in the the file up to the #pragma hdrstop. When it gets to that, it reads the compiler's internal state from the .pch file, and then starts compiling that individual file.
This means each source file typically includes a lot of headers it doesn't actually need. That, in turn, means that if you don't use pre-compiled headers, you end up with compilation that's much slower than if you hadn't done anything to support pre-compiled headers at all.
In other words, although the only part that's absolutely required is the #pragma hdrstop, which is fairly innocuous, a great deal more file re-structuring is needed to get much benefit from them--and those changes are likely to actively harmful to compilation time if you're using anything that doesn't support pre-compiled headers (and in the same way VC++ does them at that).
When precompiled headers is on every cpp source file must start with #include "stdafx.h"
So you would turn it off if you do not want to edit all the boost source files.
When precompiled headers is on stdafx.cpp "creates" the precompiled header. All other files "use" the precompiled header.

C++ Visual Studio DLL File

My objective is to create a dll and lib file so i'm following this guide
1) I created a new win32 Console Application project in VS, chose DLL as 'Application Type' and Emptied Project
2) I'm trying to create a database in C++. So I have 5 headers with ONLY function declarations.
3) Database.h is my top header, it looks like this:
#ifdef DBDLL_EXPORTS
#define DBDLL_API __declspec(dllexport)
#else
#define DBDLL_API __declspec(dllimport)
#endif
#ifndef __Database_H
#define __Database_H
#include "Table.h"
class DBDLL_API Database { ... };
#endif
4) Now with only headers, I tried compiling the project. It compiled but I don't see any DLLs or Libs anywhere in the project folder. How do I create them?
This is because headers are not compiled -- only CPP files are compiled (which pull in the headers -- a source file and all the headers it pulls in is called a "translation unit", which is the thing actually being compiled (independent of other TUs)).
So, in effect, the build system thinks you're building an empty project, and in this case generates nothing at all. Note that even if the headers are pulled in and compiled, unless an exported symbol is actually referenced somewhere, it may be optimized out. In such cases, you will get an (empty) DLL, but no .lib file (which can cause errors down the line if you have dependent projects looking for this .lib before there's anything in the DLL).
You'll need to create some CPP files that implement the functions declared in the headers. If you have everything in the headers and don't need any CPP files at all, then there's no point in having a DLL! (Since you could include the headers in any other project without needing any other dependency.)
Finally, your include guard (#ifndef ...) should encompass the entire header, including the DLL export macros, otherwise you'll eventually get macro redefinition warnings.
I would suggest using #pragma once instead of include guards since it's simpler and recognized by pretty much every compiler. I would also put the DLL macro goop into its own header (e.g. "dllmacros.h") and include that where it's needed (this will reduce duplication).

precompiled header files usage for library builders

According to this answer boost and STL headers belong into the precompiled header file (stdafx.h in the MSVC world). So I changed the headers of my dynamic link library project and moved all STL/Boost headers into the stdafx.h of my project.
Before
#include <boost/smart_ptr.hpp>
namespace XXX
{
class CLASS_DECL_BK CExampleClass // CLASS_DECL_BK is just a standard dll import/export macro
{
private:
boost::scoped_ptr<Replica> m_replica;
}
}
After
namespace XXX
{
class CLASS_DECL_BK CExampleClass
{
private:
boost::scoped_ptr<Replica> m_replica;
}
}
Now I have the advantage of decreased compile times, but all the users of my library are getting build errors (e.g. unknown boost::scoped_ptr...) because of the missing includes (which are now moved to my stdafx.h).
What could be a solution for this dilemma?
I want reduced compile times and compile errors after including my headers files are not acceptable for any users of the dll.
Could this help?
leave all includes directives as they are but duplicate them in my 'stdafx.h'? Since the stdafx.h is always included first inside any cpp file of my project I should be fine, and the users won't get any errors. Or do I loose the speed advantage if multiple includes of the same header occur in one translation unit (got header guards)?
Thanks for any hints!
You should get nearly the same speed increase when you leave the header-includes in place in the library headers and just additionally put them into stdafx.h.
Alternatively, you could add an additional define (a bulk external include guard)
// stdafx.h
#define MY_LIB_STD_HEADERS_ALREADY_INCLUDED
// library_file.h
#ifndef MY_LIB_STD_HEADERS_ALREADY_INCLUDED
#include <boost/smart_ptr.hpp>
...
#endif
But I would only do that if you are sure it helps. Just take a stopwatch and run a few re-compilations. (No need to link.) Then you'll see if there's any difference.
Aside
I'm not sure if adding all boost headers that are needed somewhere in the project is such a good idea. I'd say shared_ptrand friends, boost/foreach, maybe Boost.Format, ... are a good idea, but I'd already think twice for the Boost.RegExp headers. Note: I did not do any speed measurements, but I dimly remember a problem with the size of the pch file and some compiler hiccup. I really should do some tests.
Also check if the Boost Library in question provides forwarding headers and whether you should include them instead. Bloating the precompiled header file can have it's downsides.
you could create a build configuration for this purpose (Debug, Release, CheckDependencies). a simple way to change this would be to use the preprocessor to include/exclude the includes based on the current configuration. using this, you can test and build using debug or release (which contains the larger set of includes), then build all configurations before distribution.
to clarify, the conditional include MON_LIBRARY_VALIDATE_DEPENDENCIES is not to be used in the library headers or sources, only in the precompiled header:
// my pch:
#include <file1.hpp>
#include <file2.hpp>
// ...
#if !defined(MON_LIBRARY_VALIDATE_DEPENDENCIES)
#include <boost/stuff.hpp>
// ...
#endif
then you would append MON_LIBRARY_VALIDATE_DEPENDENCIES to the list of preprocessor definitions in the CheckDependencies configuration.
regarding guards: it should not be a problem if you are using guards under normal circumstances - compilers use optimizations to detect these cases which means they can avoid opening the file in many cases if it's been multiply included and guarded correctly. in fact, attempts to outsmart the compiler in this arena can actually slow down to process. i'd say just leave it as typical unless your library/dependencies are huge and you really have noticeable problems.
Making your compilation units selfcontained (let them include everything they use) is very desirable. This will prevent compilation errors from others that do not use precompiled headers, and as you assume, header guards will keep the cost of these extra includes minimal.
This will also have the desirable side effect that a glance at the headers will tell the users which other headers are in use in the unit, and the options of doing a compilation of the single unit without any fuzz.