C Programming Basics
#ifndef SENSOR_H
#define SENSOR_H
typedef struct { int id; int value; } Sensor;
int sensor_read(Sensor *s);
#endifThe header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?
- ATo save the result of compiling the header in a file so that compiling other source files that use the same header becomes faster
- BTo let only source files that define SENSOR_H use this header
- CTo take in the contents only once even if the same header is included several times in one source file, preventing duplicate-definition errors
Show answer and explanation
Answer: C. To take in the contents only once even if the same header is included several times in one source file, preventing duplicate-definition errors
If a.h and b.h both include sensor.h and a source file includes a.h and b.h, the contents of sensor.h are taken in twice. SENSOR_H is defined the first time, so the second time the condition #ifndef SENSOR_H is false and everything up to #endif is skipped. Without this mechanism, the struct type Sensor would be defined twice and cause a compile error. This idiom is called an include guard, and with many compilers #pragma once can be used for the same purpose.
- A. This describes precompiled headers, not what an include guard does.
- B. SENSOR_H is defined inside the header itself; it does not need to be defined on the source-file side.
- C. Correct. From the second time on, the contents are skipped.