Table of Contents

C pragma once

#pragma once is a non-standard preprocessor directive that prevents multiple inclusion of a header file. It's simpler than header guards and achieves the same goal, though it's not officially part of the C standard.

Modern compilers universally support #pragma once. Use it for cleaner headers, or use traditional header guards for portability.

Example

This example shows pragma once preventing double inclusion of a header.

// compile: gcc -o pragma pragma.c
// run: ./pragma
// description: #pragma once prevents header redefinition
 
// math_util.h
#pragma once
 
int add(int a, int b) { return a + b; }
 
// main.c
#include <stdio.h>
#include "math_util.h"
#include "math_util.h"  // second include is ignored
 
int main() {
    printf("2 + 3 = %d\n", add(2, 3));
    return 0;
}