Consider two header files a.h and b.h included in main.c. Both headers define the same macro with include guards. What will be the output when main.c is compiled and run?
#include "a.h" #include "b.h" #include <stdio.h> int main() { printf("%d\n", VALUE); return 0; } // a.h #ifndef A_H #define A_H #define VALUE 10 #endif // b.h #ifndef B_H #define B_H #undef VALUE #define VALUE 20 #endif
Include guards prevent multiple inclusions of the same header file. Different headers can define conflicting macros; the last #define wins.
a.h defines VALUE as 10 first. b.h then defines VALUE as 20 (different guards allow both inclusions). The preprocessor uses the last definition, so the program prints 20.
Why do programmers use include guards in header files?
Think about what happens if a header file is included more than once.
Include guards prevent the same header file from being included multiple times, which avoids errors like multiple definitions of the same function or variable.
Look at this header file example.h. It is supposed to have include guards but causes a compilation error when included multiple times. What is the problem?
#ifndef EXAMPLE_H #define EXAMPLE_H int add(int a, int b); #endif // EXAMPLE_H #ifndef EXAMPLE_H #define EXAMPLE_H int subtract(int a, int b); #endif // EXAMPLE_H
Check how many times the macro EXAMPLE_H is defined and what happens after the first definition.
The macro EXAMPLE_H is defined the first time, so the second block with the same guard is skipped. This causes the subtract function declaration to be missing, leading to errors.
Choose the correct syntax for include guards in a header file named myheader.h.
The macro name in #ifndef and #define must match exactly.
Option C correctly uses the same macro MYHEADER_H in both #ifndef and #define. Other options have mismatched or incorrect macros causing the guard to fail.
Given these files, how many times is the function foo() declared in the final compiled code?
// foo.h #ifndef FOO_H #define FOO_H void foo(); #endif // bar.h #ifndef BAR_H #define BAR_H #include "foo.h" #endif // main.c #include "foo.h" #include "bar.h"
Consider how include guards prevent multiple inclusions of foo.h.
Include guards in foo.h ensure that even though it is included twice (directly and via bar.h), the declaration of foo() appears only once in the compiled code.