CPP(1)

πŸ“¦
version 14-20240412 Β· 5 versions
, in ubuntu noble

πŸŽ€ CPP(1) Β· GNU πŸŽ€

Part 1 of 3 πŸ’–

Okay bestie, the manual name is cpp, and it's the GNU C preprocessor 🌸

✨ NAME ✨

cpp - The C Preprocessor πŸ¦‹

✨ SYNOPSIS ✨

Here's how you call it, no cap πŸ’…

cpp [-Dmacro[=defn]...] [-Umacro]
    [-Idir...] [-iquotedir...]
    [-M|-MM] [-MG] [-MF filename]
    [-MP] [-MQ target...]
    [-MT target...]
    infile [[-o] outfile]

Only the most useful options are in that line, so don't panic πŸ™ˆ For the full list of preprocessor-specific options, scroll down. cpp also takes most gcc driver options, which aren't listed here, so check the GCC documentation for details ✨

πŸ’– DESCRIPTION πŸ’–

Okay so, the C preprocessor (often just called cpp) is a macro processor. The C compiler uses it automatically to transform your program before compilation 🧚 It's called a macro processor because it lets you define macros, which are brief abbreviations for longer constructs. Lowkey iconic.

The C preprocessor is meant to be used only with C, C++, and Objective-C source code. In the past, people have abused it as a general text processor, and honestly? Not it 😭 It will choke on input that doesn't follow C's lexical rules. For example, apostrophes get read as the beginning of character constants, and that causes errors. You also can't count on it keeping characteristics of the input that don't matter to C-family languages.

πŸ’€ If a Makefile gets preprocessed, all the hard tabs get removed, and the Makefile won't work. Do not let this happen to your Makefile bestie.

Having said that, you can often get away with using cpp on things that aren't C. Other Algol-ish programming languages are often safe (Ada, etc.). Assembly is also fine, but with caution πŸ‘€ -traditional-cpp mode preserves more white space and is otherwise more permissive. Many of the problems can be avoided by writing C or C++ style comments instead of native language comments, and by keeping macros simple 🫢

Wherever possible, use a preprocessor geared to the language you're writing in. Modern versions of the GNU assembler have macro facilities. Most high level programming languages have their own conditional compilation and inclusion mechanism. If all else fails, try a true general text processor, such as GNU M4 πŸ’œ

C preprocessors vary in some details. This manual discusses the GNU C preprocessor, which provides a small superset of the features of ISO Standard C. In its default mode, the GNU C preprocessor doesn't do a few things the standard requires. These are features that are rarely, if ever, used, and they can cause surprising changes to the meaning of a program that doesn't expect them. To get strict ISO Standard C, use the -std=c90, -std=c99, -std=c11 or -std=c17 options, depending on which version of the standard you want. To get all the mandatory diagnostics, you must also use -pedantic πŸ”₯

This manual describes the behavior of the ISO preprocessor. To keep gratuitous differences to a minimum, the traditional preprocessor should behave the same way wherever the ISO preprocessor's behavior doesn't conflict with traditional semantics. The differences that do exist are detailed in the section Traditional Mode 🌈

For clarity, unless noted otherwise, references to CPP in this manual refer to GNU CPP πŸŽ€

🌈 OPTIONS 🌈

The cpp command expects two file names as arguments, infile and outfile. The preprocessor reads infile together with any other files it specifies with #include. All the output generated by the combined input files is written in outfile πŸ¦‹

Either infile or outfile may be -. As infile, it means read from standard input. As outfile, it means write to standard output. If either file is omitted, it's the same as if - had been specified for that file. You can also use the -o outfile option to specify the output file πŸ’…

Unless otherwise noted, or the option ends in =, all options that take an argument can have that argument right after the option, or with a space between the option and the argument. -Ifoo and -I foo have the same effect ✨

Many options have multi-letter names, so multiple single-letter options can't be grouped together. -dM is very different from -d -M πŸ’€

πŸ’… Defining and Undefining Macros

  • -D name β€” Predefine name as a macro, with definition 1.
  • -D name=definition β€” The contents of definition are tokenized and processed as if they appeared during translation phase three in a #define directive. In particular, the definition is truncated by embedded newline characters.
    • If you're invoking the preprocessor from a shell or shell-like program, you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in shell syntax.
    • If you want to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so quote the option. With sh and csh, -D'name(args...)=definition' works πŸ™Œ
  • -U name β€” Cancel any previous definition of name, either built in or provided with a -D option.

The -D and -U options are processed in the order they're given on the command line. All -imacros file and -include file options are processed after all -D and -U options 🌸

πŸ¦‹ Including Files

  • -include file β€” Process file as if "#include "file"" appeared as the first line of the primary source file. However, the first directory searched for file is the preprocessor's working directory, instead of the directory containing the main source file. If it's not found there, it's searched for in the remainder of the "#include "..." search chain as normal. If multiple -include options are given, the files are included in the order they appear on the command line.
  • -imacros file β€” Exactly like -include, except any output produced by scanning file is thrown away. Macros it defines remain defined. This lets you grab all the macros from a header without also processing its declarations. All files specified by -imacros are processed before all files specified by -include 🧚

🌸 Predefined Macros and Threads

  • -undef β€” Don't predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined.
  • -pthread β€” Define additional macros required for using the POSIX threads library. You should use this option consistently for both compilation and linking. It's supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets πŸ’–

🫢 Dependency Generation

  • -M β€” Instead of outputting the result of preprocessing, output a rule suitable for make describing the dependencies of the main source file. The preprocessor outputs one make rule containing the object file name for that source file, a colon, and the names of all the included files, including those coming from -include or -imacros command-line options.
    • Unless specified explicitly (with -MT or -MQ), the object file name is the source file's name with any suffix replaced by the object file suffix, and with any leading directory parts removed. If there are many included files, the rule is split into several lines using \-newline. The rule has no commands.
    • This option does not suppress the preprocessor's debug output, such as -dM. To avoid mixing that debug output with the dependency rules, explicitly specify the dependency output file with -MF, or use an environment variable like DEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal.
    • Passing -M to the driver implies -E, and suppresses warnings with an implicit -w πŸ‘‘
  • -MM β€” Like -M, but don't mention header files that are found in system header directories, nor header files that are included, directly or indirectly, from such a header. This implies that the choice of angle brackets or double quotes in an #include directive doesn't by itself determine whether that header appears in -MM dependency output πŸ™ˆ
  • -MF file β€” When used with -M or -MM, specifies a file to write the dependencies to. If no -MF switch is given, the preprocessor sends the rules to the same place it would send preprocessed output.
    • When used with the driver options -MD or -MMD, -MF overrides the default dependency output file.
    • If file is -, the dependencies are written to stdout.
  • -MG β€” In conjunction with an option such as -M requesting dependency generation, -MG assumes missing header files are generated files and adds them to the dependency list without raising an error. The dependency filename is taken directly from the "#include" directive without prepending any path. -MG also suppresses preprocessed output, since a missing header file makes that useless. This feature is used in automatic updating of makefiles πŸ“
  • -Mno-modules β€” Disable dependency generation for compiled module interfaces πŸ¦‹
  • -MMD β€” Same deal as -MD πŸŽ€, but this one only lists your own header files and skips the system ones 🧚
  • -fpreprocessed β€” Tells the preprocessor "hey, this file is already preprocessed, don't redo it" πŸ’… That means no macro expansion, no trigraph conversion, no escaped newline splicing, and most directives get skipped. The preprocessor still spots and removes comments, so you can hand it a file made with -C and it's totally fine 🫢 In this mode, the integrated preprocessor is basically just a tokenizer for the front ends πŸ¦‹

-fpreprocessed gets switched on automatically if your input file ends in .i, .ii or .mi. Those are the extensions GCC uses for preprocessed files made by -save-temps ✨

  • -fdirectives-only β€” When preprocessing, it handles directives but doesn't expand macros 🌸 What it does depends on whether you're also using -E or -fpreprocessed πŸ‘€

With -E, preprocessing is limited to directives like #define, #ifdef and #error πŸ“ Other stuff like macro expansion and trigraph conversion just doesn't happen. On top of that, -dD gets turned on automatically πŸ’œ

With -fpreprocessed, predefining command line macros and most builtin macros is turned off πŸ™ˆ Context-dependent macros like __LINE__ still get handled normally. This lets you compile files that were previously preprocessed with -E -fdirectives-only πŸ”₯

If you use both -E and -fpreprocessed together, the -fpreprocessed rules win πŸ‘‘ That gives you full preprocessing of files that were previously preprocessed with -E -fdirectives-only πŸ’–

  • -fdollars-in-identifiers β€” Lets $ show up in identifiers πŸ’…
  • -fextended-identifiers β€” Lets you use universal character names and extended characters in identifiers ✨ This is on by default for C99 (and later C standards) and C++ 🌈
  • -fno-canonical-system-headers β€” When preprocessing, this stops system header paths from getting shortened by canonicalization 🧚
  • -fmax-include-depth=depth β€” Sets how deep nested #includes can go πŸ¦‹ The default is 200 πŸ’œ
  • -ftabstop=width β€” Sets the distance between tab stops 🌸 This helps the preprocessor report the right column numbers in warnings or errors, even when there are tabs on the line 🫢 If the value is less than 1 or greater than 100, the option gets ignored πŸ™ˆ The default is 8 ✨
  • -ftrack-macro-expansion[=level] β€” Tracks where tokens are located across macro expansions πŸ”₯ This lets the compiler show you the current macro expansion stack when an error pops up inside a macro expansion 😭 Heads up, though: using this makes the preprocessor and compiler eat more memory πŸ’€ The level parameter lets you pick how precisely token locations get tracked, so you can drop memory usage if you need to πŸ“
    • Value 0 of level turns this option off πŸ™…
    • Value 1 tracks token locations in a degraded mode to keep memory overhead minimal 🧚 In this mode, every token that comes from expanding an argument of a function-like macro ends up with the same location 🌈
    • Value 2 tracks token locations completely πŸ’… This one is the most memory hungry 🐷

If you give this option no argument at all, the default level is 2 πŸ‘‘

Note: -ftrack-macro-expansion=2 is turned on by default ⭐
  • -fmacro-prefix-map=old=new β€” When preprocessing files that live in directory old, __FILE__ and __BASE_FILE__ get expanded as if those files lived in directory new instead πŸ¦‹ You can use . for new to turn an absolute path into a relative one, which can lead to more reproducible builds that don't depend on location 🫢 This option also affects __builtin_FILE() during compilation ✨ See also -ffile-prefix-map and -fcanon-prefix-map 🌸
  • -fexec-charset=charset β€” Sets the execution character set, which is used for string and character constants πŸ’– The default is UTF-8 🌈 charset can be any encoding the system's iconv library routine supports 🧚
  • -fwide-exec-charset=charset β€” Sets the wide execution character set, used for wide string and character constants πŸŽ€ The default is one of UTF-32BE, UTF-32LE, UTF-16BE or UTF-16LE, whichever matches the width of wchar_t and the big-endian or little-endian byte order being used for code generation πŸ”₯ Just like -fexec-charset, charset can be any encoding iconv supports 🫢 But you'll run into problems with encodings that don't fit exactly into wchar_t 😭
  • -finput-charset=charset β€” Sets the input character set, which gets translated from the input file's character set into the source character set GCC uses πŸ¦‹ If the locale doesn't say anything, or GCC can't get that info from the locale, the default is UTF-8 🌸 The locale or this command-line option can override that default πŸ’… Right now, if there's a conflict, the command-line option wins πŸ‘‘ charset can be any encoding iconv supports ✨
  • -fworking-directory β€” Turns on generation of linemarkers in the preprocessor output so the compiler knows the current working directory at the time of preprocessing 🧚 When this is on, the preprocessor emits a second linemarker right after the initial one, containing the current working directory followed by two slashes πŸ“ When that directory shows up in the preprocessed input, GCC uses it as the working directory in some debugging information formats πŸ”₯ This option gets switched on automatically when debugging information is enabled, but you can stop that with the negated form -fno-working-directory πŸ™… If the -P flag is on the command line, this option does nothing, because no #line directives get emitted whatsoever πŸ’€
  • -A predicate=answer β€” Makes an assertion with the predicate predicate and the answer answer πŸ’– This form is preferred over the older -A predicate(answer) form, which still works, because it doesn't use shell special characters 🫢
  • -A -predicate=answer β€” Cancels an assertion with the predicate predicate and the answer answer πŸ™…
  • -C β€” Don't throw away comments 🌈 All comments get passed through to the output file, except comments inside processed directives, which get deleted along with the directive πŸŽ€
Be prepared for side effects when you use -C πŸ‘€ It makes the preprocessor treat comments as tokens in their own right. For example, a comment at the start of what would be a directive line turns that line into an ordinary source line, because the first token on the line is no longer a # 😭
  • -CC β€” Don't throw away comments, even during macro expansion πŸ’… This is like -C, except comments inside macros also get passed through to the output file wherever the macro is expanded ✨

On top of the side effects of -C, -CC converts all C++-style comments inside a macro into C-style comments 🧚 That stops a later use of that macro from accidentally commenting out the rest of the source line 🫢 -CC is generally used to support lint comments 🌸

  • -P β€” Stops linemarkers from being generated in the preprocessor output πŸ¦‹ This can be useful when you run the preprocessor on something that isn't C code and will be sent to a program that might get confused by linemarkers πŸ“
  • -traditional, -traditional-cpp β€” Tries to imitate pre-standard C preprocessors, instead of ISO C preprocessors πŸ‘‘

GCC doesn't otherwise try to emulate a pre-standard C compiler πŸ™ˆ These options only work with the -E switch, or when you invoke cpp explicitly 🫢

  • -trigraphs β€” Supports ISO C trigraphs πŸ”₯ These are three-character sequences that all start with ??, which ISO C defines to stand for single characters πŸ’– For example, ??/ stands for \, so '??/n' is a character constant for a newline 🌈

By default GCC ignores trigraphs, but in standard-conforming modes it converts them πŸ’… See the -std and -ansi options πŸŽ€

  • -remap β€” Turns on special code to work around file systems that only allow very short file names, like MS-DOS 🧚
  • -H β€” Prints the name of each header file used, along with all the other normal stuff πŸ¦‹ Each name is indented to show how deep it is in the #include stack 🌸 Precompiled header files get printed too, even if they turn out to be invalid 🫢 An invalid precompiled header file gets printed with ...x, and a valid one gets printed with ...! ✨
  • -dletters β€” Makes debugging dumps during compilation, as specified by letters πŸ’œ The flags documented here are the ones relevant to the preprocessor πŸ”₯ Other letters are either handled by the compiler proper or reserved for future GCC versions, so they get silently ignored πŸ™ˆ If you specify letters whose behaviour conflicts, the result is undefined πŸ’€
    • -dM β€” Instead of the normal output, you get a list of #define directives for all the macros defined while the preprocessor runs, including predefined macros 🌈 This is a great way to find out what's predefined in your version of the preprocessor πŸ‘‘ Assuming you don't have a file called foo.h, this command shows all the predefined macros πŸŽ€
touch foo.h; cpp -dM foo.h
  • -dD β€” Like -dM, except it outputs both the #define directives and the result of preprocessing πŸ’– Both kinds of output go to the standard output file 🫢
  • -dN β€” Like -dD, but only emits the macro names, not their expansions 🧚
  • -dI β€” Outputs #include directives in addition to the result of preprocessing πŸ¦‹
  • -dU β€” Like -dD, except only macros that get expanded, or whose definedness is tested in preprocessor directives, are output πŸ’… The output is delayed until the macro is used or tested ✨ #undef directives are also output for macros that were tested but were undefined at that time 🌸
  • -fdebug-cpp β€” This one is only useful for debugging GCC πŸ™ˆ When used from CPP or with -E, it dumps debugging info about location maps πŸ”₯ Every token in the output is preceded by the dump of the map its location belongs to πŸ’€

When used from GCC without -E, this option has no effect πŸ™…

  • -I dir, -iquote dir, -isystem dir, -idirafter dir β€” Adds the directory dir to the list of directories searched for header files during preprocessing πŸŒˆπŸ’–

If dir begins with = or $SYSROOT, that = or $SYSROOT gets swapped out for the sysroot prefix 🌸. See --sysroot and -isysroot.

Directories given with -iquote only apply to the quote form of the directive, #include "file" πŸ’…. Directories given with -I, -isystem, or -idirafter apply to lookup for both #include "file" and #include <file> πŸ¦‹.

You can throw as many of these options as you want onto the command line to search several directories at once 🧚. The lookup order goes like this:

  1. For the quote form of the include directive, the directory of the current file is searched first.
  2. For the quote form, the -iquote directories are searched left-to-right, in the order they show up on the command line.
  3. -I directories are scanned left-to-right.
  4. -isystem directories are scanned left-to-right.
  5. Standard system directories are scanned.
  6. -idirafter directories are scanned left-to-right.

You can use -I to override a system header file and swap in your own version, since these directories get searched before the standard system header file directories πŸ‘‘. But don't use this option to add directories that hold vendor-supplied system header files. Use -isystem for that πŸ™ˆ.

-isystem and -idirafter also mark the directory as a system directory, so it gets the same special treatment as the standard system directories ✨.

If a standard system include directory, or a directory given with -isystem, is also given with -I, the -I option gets ignored. The directory is still searched, but as a system directory at its normal position in the system include chain. This keeps GCC's procedure for fixing buggy system headers and the ordering for the #include_next directive from getting accidentally changed 😭. If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options.

  • -I- β€” Splits the include path. This one is deprecated πŸ’€, so please use -iquote instead for the -I directories that come before -I-, then remove the -I- option.
    • Any -I directories before -I- only get searched for headers requested with #include "file". They are not searched for #include <file>.
    • Any extra -I directories after -I- get searched for all #include directives.
    • -I- also stops the directory of the current file from being used as the first search directory for #include "file". There is no way to override this effect of -I-.
  • -iprefix prefix β€” Sets prefix as the prefix for later -iwithprefix options. If the prefix represents a directory, include the final / πŸ“.
  • -iwithprefix dir, -iwithprefixbefore dir β€” Tacks dir onto the prefix you set earlier with -iprefix, then adds the resulting directory to the include search path. -iwithprefixbefore puts it where -I would, and -iwithprefix puts it where -idirafter would 🌈.
  • -isysroot dir β€” This is like the --sysroot option, but it only applies to header files. The exception is Darwin targets, where it applies to both header files and libraries. Check out --sysroot for more info πŸ“.
  • -imultilib dir β€” Uses dir as a subdirectory of the directory containing target-specific C++ headers 🧩.
  • -nostdinc β€” No searching the standard system directories for header files! Only the directories explicitly given with -I, -iquote, -isystem, and/or -idirafter get searched, plus the directory of the current file if appropriate πŸ™….
  • -nostdinc++ β€” Skips the C++-specific standard directories, but still searches the other standard directories. (This option is used when building the C++ library πŸ› οΈ.)
  • -Wcomment, -Wcomments β€” Warns whenever a comment-start sequence /* appears inside a /* comment, or whenever a backslash-newline appears in a // comment. This warning is enabled by -Wall ⚠️.
  • -Wtrigraphs β€” Warns if any trigraphs get encountered that might change the meaning of the program. Trigraphs inside comments aren't warned about, except the ones that would form escaped newlines. This option is implied by -Wall. If -Wall isn't given, this option is still enabled unless trigraphs are enabled. Want trigraph conversion without the warnings, but still the other -Wall warnings? Use -trigraphs -Wall -Wno-trigraphs πŸŽ€.
  • -Wundef β€” Warns if an undefined identifier gets evaluated in an #if directive. Those identifiers get replaced with zero πŸ”.
  • -Wexpansion-to-defined β€” Warns whenever defined shows up in the expansion of a macro, including when the macro is expanded by an #if directive. That usage isn't portable πŸ™ƒ. This warning is also enabled by -Wpedantic and -Wextra.
  • -Wunused-macros β€” Warns about macros defined in the main file that are unused 🧹. A macro counts as used if it gets expanded or tested for existence at least once. The preprocessor also warns if the macro hasn't been used at the time it gets redefined or undefined.
    • Built-in macros, macros defined on the command line, and macros defined in include files don't get warned about.
    • Note: if a macro is used, but only in skipped conditional blocks, the preprocessor reports it as unused. To avoid the warning in that case, you might improve the scope of the macro's definition, for example by moving it into the first skipped block. Or you could give it a dummy use with something like:
#if defined the_macro_causing_the_warning
#endif
  • -Wno-endif-labels β€” Doesn't warn when an #else or an #endif is followed by text. This sometimes happens in older programs with code like this:
#if FOO
...
#else FOO
...
#endif FOO

The second and third FOO should be in comments. This warning is on by default 🌸.


✨ ENVIRONMENT ✨

This section covers the environment variables that affect how CPP operates 🧚. You can use them to specify directories or prefixes to search when looking for include files, or to control dependency output.

Quick heads up: you can also specify places to search with options like -I, and control dependency output with options like -M. These take precedence over environment variables, which in turn take precedence over the configuration of GCC πŸ‘‘.

CPATH, C_INCLUDE_PATH, CPLUS_INCLUDE_PATH, OBJC_INCLUDE_PATH

Each of these variables holds a list of directories, separated by a special character, kinda like PATH, where the compiler looks for header files πŸ“‚. That special character, PATH_SEPARATOR, is target-dependent and gets determined at GCC build time. For Microsoft Windows-based targets it's a semicolon, and for almost all other targets it's a colon 🌈.

CPATH specifies a list of directories to be searched as if they were given with -I, but after any paths given with -I options on the command line. This variable is used regardless of which language is being preprocessed 🫢.

The remaining variables only apply when preprocessing the particular language they're tied to. Each one specifies a list of directories to be searched as if they were given with -isystem, but after any paths given with -isystem options on the command line πŸ’œ.

In all of these variables, an empty element tells the compiler to search its current working directory. Empty elements can appear at the beginning or end of a path. For instance, if the value of CPATH is ":/special/include", that has the same effect as -I. -I/special/include ✨.

DEPENDENCIES_OUTPUT

If this variable is set, its value specifies how to output dependencies for Make, based on the non-system header files processed by the compiler. System header files are ignored in the dependency output πŸ™….

The value of DEPENDENCIES_OUTPUT can just be a file name, in which case the Make rules get written to that file, with the target name guessed from the source file name. Or the value can have the form file target, in which case the rules are written to file using target as the target name πŸŽ€.

In other words, this environment variable is equivalent to combining the options -MM and -MF, with an optional -MT switch too πŸ’–.

SUNPRO_DEPENDENCIES

This variable is the same as DEPENDENCIES_OUTPUT (see above), except that system header files are not ignored, so it implies -M rather than -MM. However, the dependence on the main input file is omitted πŸ™ˆ.

SOURCE_DATE_EPOCH

If this variable is set, its value specifies a UNIX timestamp to be used in place of the current date and time in the __DATE__ and __TIME__ macros, so the embedded timestamps become reproducible ⏰.

The value of SOURCE_DATE_EPOCH must be a UNIX timestamp, defined as the number of seconds (excluding leap seconds) since 01 Jan 1970 00:00:00, represented in ASCII. It's identical to the output of date +%s on GNU/Linux and other systems that support the %s extension in the date command πŸ“.

The value should be a known timestamp, such as the last modification time of the source or package, and it should be set by the build process πŸ› οΈ.


✨ SEE ALSO ✨

gpl(7), gfdl(7), fsf-funding(7), gcc(1), and the Info entries for cpp and gcc πŸ“š.

Copyright (c) 1987-2024 Free Software Foundation, Inc.

You're allowed to copy, distribute, and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation πŸ¦‹. A copy of the license is included in the man page gfdl(7). This manual contains no Invariant Sections. The Front-Cover Texts are (a) (see below), and the Back-Cover Texts are (b) (see below).

(a) The FSF's Front-Cover Text is:

A GNU Manual

(b) The FSF's Back-Cover Text is:

You have freedom to copy and modify this GNU Manual, like GNU
software.  Copies published by the Free Software Foundation raise
funds for GNU development.

That's the whole tea, bestie πŸ«ΆπŸ’œ This page came from gcc-14, dated 2024-04-12, and it's CPP(1) signing off 🌈✨

πŸ“¦ where this page comes from