c-pragma-directives
Table of Contents
C pragma directives
C pragma directives use #pragma to send compiler-specific instructions. Common pragmas: #pragma once (include guard), #pragma pack (struct packing), #pragma GCC optimize (optimization level), #pragma omp (OpenMP). Pragmas are non-standard; behavior depends on compiler.
Use pragmas for compiler-specific optimizations or configuration when portability isn't critical.
Example
// compile: gcc -fopenmp -o pragma pragma.c // run: ./pragma // description: pragma directives for compiler control #pragma once // Include guard (non-standard but widely supported) #include <stdio.h> // Pack struct to 1 byte boundary #pragma pack(push, 1) struct Packed { char a; int b; char c; }; #pragma pack(pop) // Optimize this function #pragma GCC optimize("O3") int hot_loop(int n) { int sum = 0; for (int i = 0; i < n; i++) { sum += i; } return sum; } // Disable optimization for this function #pragma GCC optimize("O0") int debug_function(void) { return 42; } // OpenMP parallel loop void parallel_work(int n, int *arr) { #pragma omp parallel for for (int i = 0; i < n; i++) { arr[i] = i * 2; } } int main() { printf("Packed struct size: %zu\n", sizeof(struct Packed)); printf("Hot loop result: %d\n", hot_loop(100)); return 0; }
Common pragmas
#pragma once:
- Include guard for headers
- Non-standard but widely supported
- Cleaner than
#ifndefguards
#pragma pack:
- Control struct field alignment
#pragma pack(1): 1-byte boundary#pragma pack(push, N)and#pragma pack(pop)
#pragma GCC optimize:
- Set optimization level for following code
#pragma GCC optimize("O3")- Only GCC/Clang, not portable
#pragma omp (OpenMP):
- Parallel loop/region directives
#pragma omp parallel for- Requires
-fopenmpflag
#pragma warning (MSVC):
- Suppress compiler warnings
#pragma warning(disable:4996)- Windows-specific
#pragma message:
- Print message during compilation
- Useful for build-time notes
Portability:
- Pragmas are compiler-specific
- Unknown pragmas are ignored
- Document which compiler pragmas require
- May cause portability issues
Best practices:
- Use pragmas sparingly
- Document why pragma is needed
- Consider portable alternatives first
- Test on all target compilers
c-pragma-directives.md · Last modified: by 127.0.0.1
