C Programming Basics

#ifndef SENSOR_H
#define SENSOR_H
typedef struct { int id; int value; } Sensor;
int sensor_read(Sensor *s);
#endif

The header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?

  1. ATo save the result of compiling the header in a file so that compiling other source files that use the same header becomes faster
  2. BTo let only source files that define SENSOR_H use this header
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the code above is written inside the main function and executed?
  2. A microcontroller output register is declared and used as above. Which of the following correctly describes this declaration?
  3. Which of the following describes undefined behavior as defined by the C standard?
  4. int and unsigned int are 32 bits. Which of the following is undefined behavior according to the C standard?
  5. When the function above is compiled with gcc with optimization enabled, the check if (p == NULL) may be removed. Which of the following is the reason?