What are include guards and #pragma once?
Short answer: Include guards stop a header from being processed twice in the same translation unit (which would cause redefinition errors for types and inline functions). The classic form uses #ifndef/#define/#endif; #pragma once does the same in one line and is supported by all major compilers, but it is not part of the C standard.
#ifndef DRIVERS_UART_H
#define DRIVERS_UART_H
#include <stdint.h>
typedef struct { uint32_t baud; uint8_t parity; } uart_cfg_t;
void uart_init(const uart_cfg_t *cfg);
#endif /* DRIVERS_UART_H */
#pragma once
/* same effect */
Why a header gets included twice: main.c includes uart.h and board.h, and board.h also includes uart.h. Without guards, uart_cfg_t is defined twice and the compiler reports a redefinition.
Comparison
#ifndef guards |
#pragma once |
|
|---|---|---|
| Standard C | yes | no (but GCC, Clang, IAR, Keil, MSVC all support it) |
| Risk | two headers accidentally using the same guard name, so one is silently skipped | the same file reached through two different paths (symlinks, copies on a network drive) may be included twice |
| Typing | three lines and a unique name | one line |
Naming guards: use the path, e.g. PROJECT_DRIVERS_UART_H. Do not start them with an underscore followed by a capital letter (_UART_H): such names are reserved for the compiler and library.
MISRA C and some safety coding standards require the standard #ifndef form. Otherwise either is fine; pick one and use it consistently.
Guards do not help across translation units: if a header defines a global variable (int counter = 0;), every .c file that includes it gets its own definition and the linker reports "multiple definition". Headers should only declare (extern int counter;).