Search code examples
c++preprocessorstandard-library

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)


Solution

  • 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 */