CPP(1)
π 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β Predefinenameas a macro, with definition1.-D name=definitionβ The contents ofdefinitionare tokenized and processed as if they appeared during translation phase three in a#definedirective. 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
shandcsh,-D'name(args...)=definition'works π
-U nameβ Cancel any previous definition ofname, either built in or provided with a-Doption.
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β Processfileas if"#include "file""appeared as the first line of the primary source file. However, the first directory searched forfileis 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-includeoptions 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 scanningfileis 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-imacrosare 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 formakedescribing 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-includeor-imacroscommand-line options.- Unless specified explicitly (with
-MTor-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 likeDEPENDENCIES_OUTPUT. Debug output is still sent to the regular output stream as normal. - Passing
-Mto the driver implies-E, and suppresses warnings with an implicit-wπ
- Unless specified explicitly (with
-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#includedirective doesn't by itself determine whether that header appears in-MMdependency output π-MF fileβ When used with-Mor-MM, specifies a file to write the dependencies to. If no-MFswitch is given, the preprocessor sends the rules to the same place it would send preprocessed output.- When used with the driver options
-MDor-MMD,-MFoverrides the default dependency output file. - If
fileis-, the dependencies are written to stdout.
- When used with the driver options
-MGβ In conjunction with an option such as-Mrequesting dependency generation,-MGassumes 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.-MGalso 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-Cand 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-Eor-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 is200π-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 than1or greater than100, the option gets ignored π The default is8β¨-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 π Thelevelparameter lets you pick how precisely token locations get tracked, so you can drop memory usage if you need to π- Value
0oflevelturns this option off π - Value
1tracks 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
2tracks token locations completely π This one is the most memory hungry π·
- Value
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 directoryold,__FILE__and__BASE_FILE__get expanded as if those files lived in directorynewinstead π¦ You can use.fornewto 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-mapand-fcanon-prefix-mapπΈ-fexec-charset=charsetβ Sets the execution character set, which is used for string and character constants π The default isUTF-8πcharsetcan be any encoding the system'siconvlibrary routine supports π§-fwide-exec-charset=charsetβ Sets the wide execution character set, used for wide string and character constants π The default is one ofUTF-32BE,UTF-32LE,UTF-16BEorUTF-16LE, whichever matches the width ofwchar_tand the big-endian or little-endian byte order being used for code generation π₯ Just like-fexec-charset,charsetcan be any encodingiconvsupports π«Ά But you'll run into problems with encodings that don't fit exactly intowchar_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 isUTF-8πΈ The locale or this command-line option can override that default π Right now, if there's a conflict, the command-line option wins πcharsetcan be any encodingiconvsupports β¨-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-Pflag is on the command line, this option does nothing, because no#linedirectives get emitted whatsoever π-A predicate=answerβ Makes an assertion with the predicatepredicateand the answeranswerπ 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 predicatepredicateand the answeranswerπ-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#includestack πΈ 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 bylettersπ 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#definedirectives 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 calledfoo.h, this command shows all the predefined macros π
touch foo.h; cpp -dM foo.h
-dDβ Like-dM, except it outputs both the#definedirectives 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#includedirectives 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 β¨#undefdirectives 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 fromCPPor 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 directorydirto 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:
- For the quote form of the include directive, the directory of the current file is searched first.
- For the quote form, the
-iquotedirectories are searched left-to-right, in the order they show up on the command line. -Idirectories are scanned left-to-right.-isystemdirectories are scanned left-to-right.- Standard system directories are scanned.
-idirafterdirectories 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-iquoteinstead for the-Idirectories that come before-I-, then remove the-I-option.- Any
-Idirectories before-I-only get searched for headers requested with#include "file". They are not searched for#include <file>. - Any extra
-Idirectories after-I-get searched for all#includedirectives. -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-.
- Any
-iprefix prefixβ Setsprefixas the prefix for later-iwithprefixoptions. If the prefix represents a directory, include the final/π.-iwithprefix dir,-iwithprefixbefore dirβ Tacksdironto the prefix you set earlier with-iprefix, then adds the resulting directory to the include search path.-iwithprefixbeforeputs it where-Iwould, and-iwithprefixputs it where-idirafterwould π.-isysroot dirβ This is like the--sysrootoption, but it only applies to header files. The exception is Darwin targets, where it applies to both header files and libraries. Check out--sysrootfor more info π.-imultilib dirβ Usesdiras 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-idirafterget 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-Wallisn't given, this option is still enabled unless trigraphs are enabled. Want trigraph conversion without the warnings, but still the other-Wallwarnings? Use-trigraphs -Wall -Wno-trigraphsπ.-Wundefβ Warns if an undefined identifier gets evaluated in an#ifdirective. Those identifiers get replaced with zero π.-Wexpansion-to-definedβ Warns wheneverdefinedshows up in the expansion of a macro, including when the macro is expanded by an#ifdirective. That usage isn't portable π. This warning is also enabled by-Wpedanticand-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#elseor an#endifis 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 β¨
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
- ubuntu noble: cpp-14-s390x-linux-gnu 14-20240412-0ubuntu1cross1
- π girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms