Could you please clarify a bit more about #ifndef?How could be defined header file twice if we don't put #ifndef as we can't have two header files with the same names? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Could you please clarify a bit more about #ifndef?How could be defined header file twice if we don't put #ifndef as we can't have two header files with the same names?

12th Jan 2016, 4:42 PM
Ivailo Ivanov
Ivailo Ivanov - avatar
3 Answers
+ 1
This is called "header include guard", it is a pre-processor instruction to check if a constant is defined and if it is not - header file is included for the first time and that means include is valid and should happen, also define that constant, but if the constant is already defined - do nothing, skip header file content. Nowadays you can use something that is a bit cleaner - "#pragma once". I am not sure if it is in C++ standard, but all modern compilers are supporting it. For more info google it or check here https://en.wikipedia.org/wiki/Pragma_once
11th May 2016, 8:19 PM
Nikolay Jivkov
Nikolay Jivkov - avatar
0
Imagine you have more then just one class(and so more then just one header file) then, include guards are essentially if you wont think hours about where to include which header. Lets say you have class Car. And now, you are creating two other classes i.e. VW and Mercedes. You may would like to include your class car in both (inheritance!) and then use VW and Mercedes in your main. If you arent using include guards now, class Car is included twice in main (automatically by including VW AND Mercedes!) that will cause errors.
10th Mar 2016, 7:02 AM
Andi Lope (julandi)
Andi Lope (julandi) - avatar
0
what my professor told me, it just prevents the header files being included over and over again. with faster computers it doesn't make a HUGE difference, but back in the day, it saved a lot of time for compiling and run times.
15th Apr 2016, 4:18 AM
Aaron Reynolds
Aaron Reynolds - avatar