PCPP: A C99 Preprocessor

1.30 · active · verified Thu Apr 16

PCPP is a pure Python implementation of a C99 preprocessor. It's designed to preprocess C and C++ source code, handling directives like `#include`, `#define`, and conditional compilation. A key use case is for processing header-only C++ libraries into single-file includes and for integration with documentation tools like Doxygen. The library is actively maintained, though with an infrequent release cadence, with the latest significant update in late 2021.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the `Preprocessor` class, define custom macros, feed it C source code, and retrieve the preprocessed output. The `parse` method takes a file-like object, and `stream` returns an iterator of tokens which can be joined to form the final string.

from pcpp.preprocessor import Preprocessor
import io

# Example C code as a string
c_code = '''
#define MY_MACRO "Hello, World!"
#define VERSION 10

#if VERSION > 5
const char* message = MY_MACRO;
#else
const char* message = "Old version";
#endif

int main() {
    printf("%s\n", message);
    return 0;
}
'''

# Create a Preprocessor instance
p = Preprocessor()

# Define additional macros (optional)
p.define("DEBUG")

# Prepare input stream (from string or file)
input_stream = io.StringIO(c_code)

# Parse and preprocess the input
p.parse(input_stream)

# Get the preprocessed output
output = p.stream()

# You can iterate through the tokens or get the full string output
processed_code = ''.join(str(x) for x in output)

print(processed_code)

# Expected output for VERSION=10 and DEBUG defined:
# const char* message = "Hello, World!";
#
# int main() {
#     printf("%s\n", message);
#     return 0;
# }

view raw JSON →