CPP(1)
β¨ cpp β¨
Okay so this is the CPP(1) page from the GNU manual, bestie π Let's get into it π¦
β¨ NAME β¨
cpp β The C Preprocessor πΈ
β¨ SYNOPSIS β¨
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 shown up top, so check below for the full list of preprocessor-specific options π
. cpp also takes most gcc driver options, which aren't listed here, so if you want those deets, go read the GCC documentation π§.
β¨ DESCRIPTION β¨
Okay so the C preprocessor, which everyone calls cpp, is a macro processor. The C compiler uses it automatically to transform your program before compilation even starts π₯. It's called a macro processor because it lets you define macros, which are brief abbreviations for longer constructs. Iconic behavior, honestly π.
The C preprocessor is meant to be used only with C, C++, and Objective-C source code. In the past people abused it as a general text processor, but ngl that's not its vibe π. It will choke on input that doesn't follow C's lexical rules. For example, apostrophes get read as the start of character constants, and that causes errors π. You also can't count on it keeping stuff that doesn't matter to C-family languages. If you preprocess a Makefile, all the hard tabs get removed, and the Makefile won't work.
Warning, bestie: if you run a Makefile through cpp, every hard tab gets stripped out and the Makefile will not work. Do not do this to your Makefile π.
Having said that, you can lowkey get away with using cpp on things that aren't C. Other Algol-ish languages are often safe (Ada, etc.), and assembly is okay too, as long as you're careful π¦. -traditional-cpp mode keeps more white space and is generally more permissive β¨. A lot of problems go away if you write C or C++ style comments instead of native language comments and keep your macros simple π«Ά.
Wherever possible, use a preprocessor built for 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 mechanisms. If all else fails, try a true general text processor, like GNU M4 π.
C preprocessors vary a little. This manual talks about the GNU C preprocessor, which gives you a small superset of the features of ISO Standard C π. In its default mode, the GNU C preprocessor skips a few things the standard requires. These are features that are rarely, if ever, used, but they can cause surprising changes to the meaning of a program that doesn't expect them π. If you want strict ISO Standard C, use -std=c90, -std=c99, -std=c11 or -std=c17, depending on which version of the standard you want. To get all the mandatory diagnostics, you must also use -pedantic π
.
This manual describes how the ISO preprocessor behaves. To cut down on gratuitous differences, wherever the ISO preprocessor doesn't clash with traditional semantics, the traditional preprocessor should act the same way π§. The differences that do exist are spelled out in the section Traditional Mode.
For clarity, unless noted otherwise, any mention of CPP in this manual means GNU CPP π.
β¨ OPTIONS β¨
The cpp command expects two file names as arguments, infile and outfile. The preprocessor reads infile, along with any other files it pulls in with #include. All the output from the combined input files gets written to outfile π.
Either infile or outfile can be -. As infile, it means read from standard input. As outfile, it means write to standard output. If either file is left out, it works the same as if - had been given for that file. You can also use the -o outfile option to pick the output file β¨.
Unless otherwise noted, or the option ends in =, every option that takes an argument can have that argument right after the option, or with a space between the option and the argument. So -Ifoo and -I foo have the same effect π.
Lots of options have multi-letter names, so you can't group multiple single-letter options together. -dM is very different from -d -M π.
-D nameβ Predefinesnameas a macro, with the definition1πΈ.-D name=definitionβ The contents ofdefinitionget tokenized and processed as if they showed up during translation phase three in a#definedirective. The definition gets cut off by any embedded newline characters βοΈ. If you're calling the preprocessor from a shell (or something shell-like), you might need the shell's quoting syntax to protect characters like spaces, since those mean something to the shell π. If you want a function-like macro on the command line, put its argument list in parentheses before the equals sign (if there is one). Parentheses mean stuff to most shells, so quote the option. Withshandcsh,-D'name(args...)=definition'works π§.-Dand-Uoptions get processed in the order they show up on the command line. All-imacros fileand-include fileoptions get processed after all the-Dand-Uoptions π₯.
-U nameβ Cancels any previous definition ofname, whether it was built in or set with a-Doption π¦.-include fileβ Processesfileas if#include "file"appeared as the very first line of the primary source file. The big difference is that the first directory searched forfileis the preprocessor's working directory, not the directory with the main source file. If it's not found there, it's searched for in the rest of the usual#include "..."search chain π§. If you give multiple-includeoptions, the files get included in the order they appear on the command line π .-imacros fileβ Exactly like-include, except any output produced by scanningfilegets thrown away. The macros it defines stay defined. This lets you grab all the macros from a header without also processing its declarations π. All files given with-imacrosget processed before all files given with-includeπ.-undefβ Doesn't predefine any system-specific or GCC-specific macros. The standard predefined macros stay defined π.-pthreadβ Defines extra macros needed for using the POSIX threads library π§΅. Use this option consistently for both compilation and linking, bestie. It's supported on GNU/Linux targets, most other Unix derivatives, and also on x86 Cygwin and MinGW targets π.-Mβ Instead of outputting the preprocessed result, this outputs a rule suitable formakethat describes 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. That includes the ones coming from-includeor-imacroscommand-line options π. Unless you set it explicitly (with-MTor-MQ), the object file name is the source file's name with any suffix swapped for the object file suffix and with any leading directory parts removed π. If there are a lot of included files, the rule gets split into several lines using\-newlineβ¨. The rule has no commands π .
Heads up:-Mdoesn't suppress the preprocessor's debug output, like-dM. To keep that debug output from mixing with your dependency rules, specify the dependency output file explicitly with-MF, or use an environment variable likeDEPENDENCIES_OUTPUTπ. Debug output still goes to the regular output stream like normal π§.
- Passing
-Mto the driver implies-E, and suppresses warnings with an implicit-wπ.
-MMβ Like-M, but it doesn't mention header files found in system header directories, or header files included (directly or indirectly) from one of those system headers π¦. This also means the choice of angle brackets or double quotes in an#includedirective doesn't, on its own, decide whether that header shows up in-MMdependency output π.-MF fileβ When used with-Mor-MM, this picks a file to write the dependencies to. If you don't give-MF, 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 π. Iffileis-, the dependencies get written to stdout π.-MGβ Used together with an option like-Mthat asks for dependency generation,-MGassumes missing header files are generated files. It adds them to the dependency list without raising an error β¨. The dependency filename is taken straight from the#includedirective, without any path prepended π§.-MGalso suppresses preprocessed output, since a missing header file makes that useless π. This feature is used in automatic updating of makefiles π«Ά.-MPβ This option tells CPP to add a phony target for each dependency other than the main file, so each one depends on nothing π. These dummy rules work around errorsmakegives if you remove header files without updating the Makefile to match π. This is typical output:
test.o: test.c test.h
test.h:
-MT targetβ Changes the target of the rule emitted by dependency generation π―. By default, CPP takes the name of the main input file, deletes any directory components and any file suffix like.c, and appends the platform's usual object suffix. That result is the target π¦. An-MToption sets the target to be exactly the string you give it. If you want multiple targets, you can put them in a single argument to-MT, or use multiple-MToptions π . For example,-MT '$(objpfx)foo.o'might give:
$(objpfx)foo.o: foo.c
-MQ targetβ Same as-MT, but it quotes any characters that are special to Make π.-MQ '$(objpfx)foo.o'gives:
$$(objpfx)foo.o: foo.c
The default target gets quoted automatically, as if it had been given with -MQ π.
-MDβ-MDis equivalent to-M -MF file, except that-Eis not implied π₯. The driver figures outfilebased on whether an-ooption is given. If it is, the driver uses that argument but with a suffix of.d. Otherwise, it takes the name of the input file, removes any directory components and suffix, and applies a.dsuffix π§. If-MDis used together with-E, any-oswitch is understood to name the dependency output file. But if-MDis used without-E, each-ois understood to name a target object file πΈ. Since-Eisn't implied,-MDcan generate a dependency output file as a side effect of the compilation process β¨.-MMDβ Like-MD, except it only mentions user header files, not system header files π.-fpreprocessedβ okay bestie, this tells the preprocessor "hey, this file is ALREADY preprocessed, don't redo it" π β¨ It skips macro expansion, trigraph conversion, escaped newline splicing, and processing of most directives π It still recognizes and removes comments though, so you can pass a file preprocessed with-Cto the compiler without any drama π¦ In this mode the integrated preprocessor is literally just a tokenizer for the front ends π§
-fpreprocessed is implicit if the input file has one of the extensions .i, .ii or .mi. These are the extensions GCC uses for preprocessed files created by -save-temps πΈ
-fdirectives-onlyβ handle directives π but do NOT expand macros π ββοΈ
The behavior of this one depends on -E and -fpreprocessed, so pay attention π
- With
-E, preprocessing is limited to handling directives like"#define","#ifdef", and"#error". Other preprocessor operations, like macro expansion and trigraph conversion, are not performed. Also the-dDoption is implicitly enabled π - With
-fpreprocessed, predefinition of command line and most builtin macros is disabled. Macros like"__LINE__", which are contextually dependent, are handled normally. This enables compiling files previously preprocessed with"-E -fdirectives-only"β¨ - With both
-Eand-fpreprocessed, the rules for-fpreprocessedtake precedence. This enables full preprocessing of files previously preprocessed with"-E -fdirectives-only"π
-fdollars-in-identifiersβ lets you use$in identifiers π-fextended-identifiersβ accepts universal character names in identifiers π This one is enabled by default for C99 (and later C standard versions) and C++, so you basically don't have to ask π-fno-canonical-system-headersβ when preprocessing, this stops system header paths from getting shortened with canonicalization π«Ά-ftabstop=widthβ sets the distance between tab stops π This helps the preprocessor report correct column numbers in warnings or errors, even if tabs show up on the line π If the value is less than1or greater than100, the option is ignored. The default is8π-ftrack-macro-expansion[=level]β tracks where tokens are across macro expansions π΅οΈββοΈ This lets the compiler show the current macro expansion stack when a compilation error happens inside a macro expansion, which is SO helpful. The catch? Using it makes the preprocessor and the compiler eat more memory π The level parameter lets you pick how precise the token location tracking is, so you can cut down on memory if you need to. Level0turns this option off π ββοΈ Level1tracks token locations in a degraded mode for minimal memory overhead; in this mode, all tokens resulting from the expansion of an argument of a function-like macro have the same location. Level2tracks token locations completely, and it is the MOST memory hungry option π If you give this option no argument, the default parameter value is2π₯
Note that -ftrack-macro-expansion=2 is activated by default π
-fmacro-prefix-map=old=newβ when preprocessing files living in the directory old, it expands the__FILE__and__BASE_FILE__macros as if those files lived in directory new instead πΊοΈ You can use.for new to change an absolute path into a relative one, which can lead to more reproducible, location-independent builds π¦ This option also affects__builtin_FILE()during compilation. See also-ffile-prefix-mapπ§-fexec-charset=charsetβ sets the execution character set, which is used for string and character constants π¬ The default isUTF-8. charset can be any encoding supported by the system'siconvlibrary routine πΈ-fwide-exec-charset=charsetβ sets the wide execution character set, used for wide string and character constants π The default isUTF-32orUTF-16, whichever matches the width ofwchar_t. Just like-fexec-charset, charset can be any encoding supported by the system'siconvlibrary routine π
Heads up: you will have problems with encodings that do not fit exactly in wchar_t π
-finput-charset=charsetβ sets the input character set, which is used for translating from the input file's character set to the source character set GCC uses π₯ If the locale doesn't specify one, or GCC can't get that info from the locale, the default isUTF-8. This can be overridden by either the locale or this command-line option. Right now the command-line option takes precedence if there's a conflict π charset can be any encoding supported by the system'siconvlibrary routine π«Ά-fworking-directoryβ turns on linemarkers in the preprocessor output so the compiler knows the current working directory at the time of preprocessing π When this is enabled, the preprocessor emits, after the initial linemarker, a second linemarker with the current working directory followed by two slashes. GCC uses this directory (if it's in the preprocessed input) as the working directory in some debugging information formats π This option is implicitly enabled if debugging information is enabled, but you can stop it with the negated form-fno-working-directoryπ ββοΈ If the-Pflag is in the command line, this option has no effect, since no#linedirectives 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 is still supported, because it doesn't use shell special characters π-A -predicate=answerβ cancels an assertion with the predicate predicate and the answer answer π«-Cβ do NOT discard comments π¬ All comments get passed through to the output file, EXCEPT comments in processed directives, which get deleted along with the directive ποΈ
Be prepared for side effects when using-C! It makes the preprocessor treat comments as tokens in their own right. For example, comments at the start of what would be a directive line turn that line into an ordinary source line, since the first token on the line is no longer a#π
-CCβ do not discard comments, INCLUDING during macro expansion π This is like-C, except comments contained within macros also get passed through to the output file where the macro is expanded π§
In addition to the side effects of -C, the -CC option converts all C++-style comments inside a macro into C-style comments. This is to stop 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β inhibits generating linemarkers in the preprocessor output π«π This might be useful when running the preprocessor on something that isn't C code and is going to a program that might get confused by the linemarkers πΈ-traditional,-traditional-cppβ try to imitate pre-standard C preprocessors, instead of ISO C preprocessors π°οΈ
GCC doesn't otherwise try to emulate a pre-standard C compiler, and these options are only supported with the -E switch, or when invoking CPP explicitly π
-trigraphsβ supports ISO C trigraphs πΊ These are three-character sequences, all starting with??, that 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β enables special code to work around file systems that only allow super short file names, like MS-DOS πΎ-Hβ prints the name of each header file used, on top of your 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 is printed with...xand a valid one with...!β β-dlettersβ tells the compiler to make debugging dumps as specified by letters π The flags documented here are the ones relevant to the preprocessor. Other letters are interpreted by the compiler proper, or reserved for future versions of GCC, and get silently ignored π€«
If you specify letters whose behavior conflicts, the result is undefined. Undefined means anything can happen, bestie, so maybe don't π
-dMβ instead of the normal output, generates a list of#definedirectives for all the macros defined during the execution of the preprocessor, including predefined macros π This is a way to find out what's predefined in your version of the preprocessor π§ Assuming you have no filefoo.h, the command below shows all the predefined macros:
touch foo.h; cpp -dM foo.h
-dDβ like-dM, except in two ways: it does NOT include the predefined macros, and 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 gets tested in preprocessor directives, are output π― The output is delayed until the use or test of the macro, and#undefdirectives are also output for macros that were tested but undefined at the time π¦
-fdebug-cppβ this one is ONLY useful for debugging GCC π οΈ When used fromCPPor with-E, it dumps debugging information 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, then the = or $SYSROOT gets replaced by the sysroot prefix. See --sysroot and -isysroot π§π
Okay so bestie, 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 any number or combo of these options on the command line to search for header files in several directories at once πβ¨ Here's the lookup order, and it's giving very organized:
- For the quote form of the include directive, the directory of the current file gets searched first.
- For the quote form, the directories given by
-iquoteoptions get searched left-to-right, in the order they show up on the command line. - Directories given with
-Ioptions get scanned left-to-right. - Directories given with
-isystemoptions get scanned left-to-right. - Standard system directories get scanned.
- Directories given with
-idirafteroptions get 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 π
ββοΈ
The -isystem and -idirafter options 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 is ignored. The directory still gets searched, but as a system directory at its normal spot in the system include chain. This is so GCC's procedure to fix buggy system headers and the ordering for the #include_next directive don't get accidentally changed π₯Ί If you really need to change the search order for system directories, use the -nostdinc and/or -isystem options.
-I-β Split the include path π This one is deprecated, so please don't reach for it. Use-iquoteinstead for-Idirectories before the-I-, and remove the-I-option.
β οΈ Deprecated alert!-I-is deprecated. Use-iquoteinstead for-Idirectories before the-I-, and remove the-I-option.
Any directories given with -I options before -I- only get searched for headers requested with #include "file". They are not searched for #include <file>. If extra directories are given with -I options after the -I-, those directories get searched for all #include directives. Also, -I- stops the directory of the current file from being used as the first search directory for #include "file", and there is no way to override that effect of -I- π
ββοΈ
-iprefix prefixβ Setprefixas the prefix for subsequent-iwithprefixoptions. If the prefix represents a directory, include the final/π-iwithprefix dir,-iwithprefixbefore dirβ Tackdironto the prefix you set earlier with-iprefix, and add the resulting directory to the include search path.-iwithprefixbeforeputs it in the same place-Iwould, while-iwithprefixputs it where-idirafterwould π§-isysroot dirβ This one is like the--sysrootoption, but it only applies to header files (except for Darwin targets, where it applies to both header files and libraries). See the--sysrootoption for more information π-imultilib dirβ Usediras a subdirectory of the directory containing target-specific C++ headers π-nostdincβ Don't search the standard system directories for header files. Only the directories explicitly given with-I,-iquote,-isystem, and/or-idirafteroptions (and the directory of the current file, if appropriate) get searched π-nostdinc++β Don't search the C++-specific standard directories, but do still search the other standard directories. (This option is used when building the C++ library.) π-Wcomment,-Wcommentsβ Warn whenever a comment-start sequence/*appears in a/*comment, or whenever a backslash-newline shows up in a//comment. This warning is enabled by-Wallπ-Wtrigraphsβ Warn if any trigraphs are encountered that might change the meaning of the program. Trigraphs within comments don't get warned about, except those that would form escaped newlines. This option is implied by-Wall. If-Wallisn't given, this option is still enabled unless trigraphs are enabled. To get trigraph conversion without warnings, but still get the other-Wallwarnings, use-trigraphs -Wall -Wno-trigraphsπ«-Wundefβ Warn if an undefined identifier is evaluated in an#ifdirective. Such identifiers get replaced with zero π-Wexpansion-to-definedβ Warn wheneverdefinedis encountered in the expansion of a macro (including the case where the macro is expanded by an#ifdirective). Such usage is not portable. This warning is also enabled by-Wpedanticand-Wextraπ«-Wunused-macrosβ Warn about macros defined in the main file that are unused. A macro counts as used if it's expanded or tested for existence at least once. The preprocessor also warns if the macro hasn't been used by the time it's 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 actually used, but only used in skipped conditional blocks, then the preprocessor reports it as unused. To avoid the warning in that case, you might improve the scope of the macro's definition by, for example, moving it into the first skipped block. Alternatively, you could provide a dummy use with something like:
#if defined the_macro_causing_the_warning
#endif
-Wno-endif-labelsβ Don't warn whenever an#elseor an#endifis followed by text. This sometimes happens in older programs with code of the form π°οΈ
#if FOO
...
#else FOO
...
#endif FOO
The second and third FOO should be in comments. This warning is on by default.
β¨ ENVIRONMENT β¨
This section is all about the environment variables that change how CPP operates π You can use them to specify directories or prefixes to use when searching for include files, or to control dependency output.
Note that you can also specify places to search using options such as -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 variable's value is a list of directories separated by a special character, much like PATH, in which to look for header files. The special character, PATH_SEPARATOR, is target-dependent and determined at GCC build time. For Microsoft Windows-based targets it is a semicolon, and for almost all other targets it is a colon π§©
CPATH specifies a list of directories to be searched as if specified with -I, but after any paths given with -I options on the command line. This environment variable is used regardless of which language is being preprocessed πΈ
The remaining environment variables only apply when preprocessing the particular language they're named for. Each one specifies a list of directories to be searched as if specified with -isystem, but after any paths given with -isystem options on the command line.
In all these variables, an empty element instructs 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 be just a file name, in which case the Make rules are written to that file, guessing the target name from the source file name. Or the value can have the form file target, in which case the rules are written to file 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 replacement of the current date and time in the __DATE__ and __TIME__ macros, so that 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-2019 Free Software Foundation, Inc. π
Permission is granted 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 a wrap on CPP(1), bestie! π Huge thanks to gcc-9 π¦ for this one, last touched on 2022-05-27 πΈ Now go preprocess something iconic, you absolute legend ππ
π¦ where this page comes from
- ubuntu jammy: cpp-9-sparc64-linux-gnu 9.5.0-1ubuntu1~22.04cross1
- π girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms