CPP(1)
π cpp: The C Preprocessor (GNU) π
section 1 Β· part 1 of 3 β¨
β¨ 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]
okay so these are only the most useful options bestie π«Ά there's a more complete list of preprocessor-specific options further down. cpp also takes most gcc driver options, but those aren't listed here, so check the GCC docs for the details π.
π¦ DESCRIPTION π¦
okay so the C preprocessor, aka cpp, is a macro processor that the C compiler runs automatically to transform your program before compilation β¨. It's called a macro processor bc it lets you define macros, which are brief abbreviations for longer constructs π
.
The C preprocessor is meant to be used only with C, C++, and Objective-C source code π. People have abused it as a general text processor in the past π, and it will choke on input that doesn't follow C's lexical rules. Like, apostrophes get read as the start of character constants and cause 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 π.
π¨ Heads up bestie: if you run a Makefile through cpp, every hard tab gets stripped out and the Makefile will NOT work. Not cute π.
Having said that, you can often get away with using cpp on stuff that isn't C π. Other Algol-ish programming languages are usually safe (Ada, etc.) π§. Assembly is also fine, but with caution β οΈ. -traditional-cpp mode preserves more white space and is otherwise more permissive π. A lot of the problems can be avoided by writing C or C++ style comments instead of native language comments, and by keeping your 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, like GNU M4 π.
C preprocessors vary a bit in the details π. This manual is about the GNU C preprocessor, which gives you a small superset of the features of ISO Standard C β¨. In its default mode, it 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 π.
β οΈ Default mode is a little extra: the GNU preprocessor's default mode doesn't do a few things the standard requires, and that can quietly change what your program means.
To get 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 the behavior of the ISO preprocessor π«Ά. To cut down on gratuitous differences, where the ISO preprocessor's behavior doesn't conflict with traditional semantics, the traditional preprocessor should behave the same way too π¦. The differences that do exist are detailed in the section Traditional Mode π.
For clarity, unless noted otherwise, references to CPP in this manual mean 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 gets written to outfile β¨.
Either infile or outfile may be -. As infile, that 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 name 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 argument. So -Ifoo and -I foo do the exact same thing π
.
Lots of options have multi-letter names, so you can't group single-letter options together. -dM is very different from -d -M π.
-D nameβ Predefinenameas a macro, with definition1πΈ.-D name=definitionβ Thedefinitiongets tokenized and processed as if it showed up during translation phase three in a#definedirective. Embedded newline characters truncate the definition βοΈ.- If you're calling the preprocessor from a shell or shell-like program, you might need the shell's quoting syntax to protect characters like spaces that mean something in shell syntax π.
- 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 mean stuff to most shells, so quote the option. With
shandcsh,-D'name(args...)=definition'works π§ . -Dand-Uoptions are processed in the order they're given on the command line. All-imacros fileand-include fileoptions get processed after all-Dand-Uoptions π₯.
-U nameβ Cancel any previous definition ofname, whether it was built in or provided with a-Doption π«.-include fileβ Processfileas if#include "file"appeared as the first line of the primary source file. The difference is that the first directory searched forfileis the preprocessor's working directory, not the directory containing the main source file. If it's not found there, it gets searched for in the rest of the#include "..."search chain as normal π.- If you give multiple
-includeoptions, the files get included in the order they appear on the command line π.
- If you give multiple
-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 specified by
-imacrosare processed before all files specified by-includeπ.
- All files specified by
-undefβ Don't predefine any system-specific or GCC-specific macros. The standard predefined macros stay defined π.-pthreadβ Defines the additional macros required for using the POSIX threads library. 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 π.-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 from-includeor-imacroscommand-line options π.- Unless you specify it explicitly (with
-MTor-MQ), the object file name is the name of the source file with any suffix replaced by the object file suffix, and with any leading directory parts removed. If there are lots of included files, the rule gets split across 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 still goes to the regular output stream as normal π. - Passing
-Mto the driver implies-E, and suppresses warnings with an implicit-wπ€«.
- Unless you specify it explicitly (with
-MMβ Like-M, but don't mention header files that are found in system header directories, or header files that get included, directly or indirectly, from such a header π°.- This means that choosing angle brackets or double quotes in an
#includedirective doesn't, on its own, decide whether that header shows up in-MMdependency output π«Ά.
- This means that choosing angle brackets or double quotes in an
-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 get written to stdout π¨οΈ.
- When used with the driver options
-MGβ Used together with an option like-Mthat requests 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 directly from the#includedirective 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 π§.
This is what -MP does π οΈ: it tells CPP to add a phony target for each dependency other than the main file, causing each one to depend on nothing. These dummy rules work around the errors make gives if you remove header files without updating the Makefile to match. Here's 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 such as.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 specify. If you want multiple targets, you can specify them as a single argument to-MT, or use multiple-MToptions π.
- An
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 π‘οΈ.- The default target is automatically quoted, as if it were given with
-MQπ .
- The default target is automatically quoted, as if it were given with
-MQ '$(objpfx)foo.o' gives:
$$(objpfx)foo.o: foo.c
-fpreprocessed: okay so this one tells the preprocessor the input is already preprocessed π§. That means it skips the usual stuff like macro expansion, trigraph conversion, escaped newline splicing, and most directives. It still spots and removes comments, so you can pass a file made with-Cto the compiler with zero drama. In this mode the integrated preprocessor is basically just a tokenizer for the front ends.-fpreprocessedis implicit if the input file ends in.i,.iior.mi, which are the extensions GCC uses for preprocessed files made by-save-tempsπ-fdirectives-only: handles directives but does not expand macros π¦ How it behaves depends on-Eand-fpreprocessed:- With
-E, preprocessing is limited to directives like"#define","#ifdef", and"#error". Macro expansion and trigraph conversion don't happen. Also,-dDgets turned on implicitly. - With
-fpreprocessed, predefining command line and most builtin macros is disabled. Contextual ones like__LINE__are still handled normally, which is what lets you compile files that were previously preprocessed with-E -fdirectives-onlyπΈ - With both
-Eand-fpreprocessed, the-fpreprocessedrules win. That's how you get full preprocessing of files that were previously run through-E -fdirectives-onlyπ
- With
-fdollars-in-identifiers: lets$show up inside identifiers. Main character energy π-fextended-identifiers: accepts universal character names and extended characters in identifiers β¨ This one's on by default for C99 (and later C standard versions) and C++, so you're probably already using it and didn't even know π-fno-canonical-system-headers: when preprocessing, stops the system header paths from getting shortened with canonicalization π§-fmax-include-depth=depth: sets how deep nested#includes can go. Default is200π-ftabstop=width: sets the distance between tab stops. This helps the preprocessor report correct 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. Default is8.-ftrack-macro-expansion[=level]: tracks token locations across macro expansions π This lets the compiler show the current macro expansion stack when an error happens inside a macro. Heads up though, it makes the preprocessor and compiler eat more memory. The level parameter lets you pick how precise the tracking is, so you can dial down memory use if you need to:0turns this option off.1tracks locations in a degraded mode for minimal memory overhead. In this mode, every token that comes from expanding an argument of a function-like macro gets the same location.2tracks locations completely. This is the most memory hungry one π₯
If you give it no argument, the default parameter value is 2. Also, -ftrack-macro-expansion=2 is activated by default, bestie.
-fmacro-prefix-map=old=new: when preprocessing files in directory old,__FILE__and__BASE_FILE__expand as if the files lived in directory new instead πΊοΈ Use.for new to turn an absolute path into a relative one, which can make builds more reproducible and location-independent. This also affects__builtin_FILE()during compilation. See also-ffile-prefix-map.-fexec-charset=charset: sets the execution character set for string and character constants. Default isUTF-8. charset can be any encoding the system'siconvlibrary routine supports π-fwide-exec-charset=charset: sets the wide execution character set for wide string and character constants π The default is one ofUTF-32BE,UTF-32LE,UTF-16BE, orUTF-16LE, whichever matches the width ofwchar_tand the big-endian or little-endian byte order used for code generation. Like-fexec-charset, charset can be anyiconvencoding, but you'll run into problems with encodings that don't fit exactly inwchar_tπ-finput-charset=charset: sets the input character set, which is used to translate the input file's characters into the source character set GCC uses πΈ If the locale doesn't specify one, or GCC can't get it from the locale, the default isUTF-8. The locale or this command-line option can override it, but the command-line option wins if there's a conflict. charset can be anyiconvencoding.-fworking-directory: turns on linemarkers in the preprocessor output that tell the compiler what the working directory was at preprocessing time π When it's on, after the initial linemarker the preprocessor emits a second one with the current working directory followed by two slashes. GCC uses that directory, when it's in the preprocessed input, as the working directory in some debugging information formats. This is implicitly enabled when debugging info is on, but you can block it with the negated form-fno-working-directory. If-Pis on the command line, this option does nothing, 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. That one still works, but this one doesn't use shell special characters, so it's way less drama.-A -predicate=answer: cancels an assertion with the predicate predicate and the answer answer π«-C: stops discarding 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 here! With-C, the preprocessor treats comments as tokens in their own right. So comments sitting at the start of what would be a directive line turn that line into an ordinary source line, since the first token isn't a#anymore π¬-CC: stops discarding comments, including during macro expansion π«Ά It's like-C, except comments inside macros also get passed through to the output wherever the macro is expanded. On top of the-Cside effects,-CCconverts all C++-style comments inside a macro into C-style comments. This stops a later use of that macro from accidentally commenting out the rest of the source line.-CCis generally used to support lint comments π§Ή-P: inhibits linemarkers in the preprocessor output π This might be useful when you're running the preprocessor on something that isn't C code and will get sent to a program that could get confused by linemarkers.-traditional,-traditional-cpp: tries to imitate pre-standard C preprocessors instead of ISO C preprocessors π°οΈ Note that GCC doesn't otherwise try to emulate a pre-standard C compiler, and these options are only supported with the-Eswitch or when you invokeCPPexplicitly.-trigraphs: supports ISO C trigraphs β¨ These are three-character sequences that all start with??, and ISO C defines them 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-stdand-ansioptions.-remap: enables special code to work around file systems that only permit very short file names, like MS-DOS πΎ-H: prints the name of each header file used, on top of the other normal stuff π Each name is indented to show how deep it sits in the#includestack. Precompiled header files get printed too, even if they turn out to be invalid. An invalid one shows up with...x, and a valid one shows up 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 interpreted by the compiler proper, or reserved for future versions of GCC, so they're silently ignored. If you specify letters whose behavior conflicts, the result is undefined, so don't π ββοΈ-dM: instead of the normal output, you get a list of#definedirectives for all the macros defined during preprocessing, predefined ones included π It's a way of finding out what's predefined in your version of the preprocessor. Assuming you have no filefoo.h, this command shows all the predefined macros:
touch foo.h; cpp -dM foo.h
-dD: like-dM, except it leaves out 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 it 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 macro is used or tested. Also,#undefdirectives are output for macros that were tested but were undefined at the 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 dir to the list of directories searched for header files during preprocessing πβ¨
okay bestie, the = and $SYSROOT thing is simple: if dir starts with = or $SYSROOT, that prefix gets swapped out for the sysroot prefix πΊοΈ. Check out --sysroot and -isysroot for the full tea β.
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 stack as many of these as you want on the command line to search several directories for header files π. The lookup order goes like this β¨:
- For the quote form of the include directive, the directory of the current file gets searched first π .
- For the quote form of the include directive, 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 full of vendor-supplied system header files π
ββοΈ. Use -isystem for that instead π.
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, also shows up with -I, the -I option gets ignored π. The directory still gets searched, but as a system directory at its normal spot 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 messed up by accident π§. 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 option is deprecated, so please use-iquoteinstead for-Idirectories that come before the-I-, and then remove the-I-option π«.
Any directories given with -I options before -I- only get searched for headers requested with #include "file". They don't get searched for #include <file> π. If extra directories are given with -I options after the -I-, those get searched for all #include directives π.
On top of that, -I- stops the directory of the current file from being used as the first search directory for #include "file". There's no way to override this effect of -I- π.
-iprefix prefixβ Sets prefix as the prefix for later-iwithprefixoptions π§. If the prefix is a directory, make sure you 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 π€οΈ.-iwithprefixbeforeputs it in the same spot-Iwould.-iwithprefixputs it where-idirafterwould π¦.-isysroot dirβ This one's 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 the--sysrootoption for more info π .-imultilib dirβ Uses dir as a subdirectory of the directory that holds target-specific C++ headers π§.-nostdincβ Doesn't search the standard system directories for header files π«ποΈ. Only the directories explicitly given with-I,-iquote,-isystem, and/or-idirafteroptions get searched, plus the directory of the current file if it's relevant π―.-nostdinc++β Doesn't search the C++-specific standard directories for header files, but still searches the other standard directories πΈ. (This option is used when building the C++ library π οΈ.)-Wcomment,-Wcommentsβ Warns whenever a comment-start sequence/*shows up inside a/* comment, or whenever a backslash-newline shows up in a//comment π. This warning is turned on by-Wallβ¨.-Wtrigraphsβ Warns if any trigraphs get encountered that could change the meaning of the program β οΈ. Trigraphs inside comments don't get warned about, except for 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 π§. To get trigraph conversion without warnings, but still get the other -Wall warnings, use -trigraphs -Wall -Wno-trigraphs π
.
-Wundefβ Warns if an undefined identifier gets evaluated in an#ifdirective π« . Those identifiers get replaced with zero 0οΈβ£.-Wexpansion-to-definedβ Warns wheneverdefinedshows up in the expansion of a macro, including when the macro gets expanded by an#ifdirective π. This usage isn't portable π©. This warning is also turned on by-Wpedanticand-Wextraπ.-Wunused-macrosβ Warns about macros defined in the main file that never get used π΅οΈββοΈ. A macro counts as used if it gets expanded or tested for existence at least once π. The preprocessor also warns if a macro hasn't been used by 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 actually used, but only inside 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 π§©. Or you could give it a dummy use with something like this:
#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 π .
You can also specify places to search using options like -I, and control dependency output with options like -M π«Ά. These take precedence over environment variables, and environment variables 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, kinda likePATHποΈ. You look for header files in these directories. The special character,"PATH_SEPARATOR", depends on the target and gets set at GCC build time π οΈ. For Microsoft Windows-based targets it's a semicolon β¨, and for almost every other target 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 environment variable gets used no matter 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 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 show up 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 the compiler processes π οΈ. System header files get ignored in the dependency output π ββοΈ.
The value of DEPENDENCIES_OUTPUT can just be a file name. In that case the Make rules get written to that file, and the target name gets guessed from the source file name π―. Or the value can have the form file target, in which case the rules get 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 is the same asDEPENDENCIES_OUTPUT, except system header files aren't ignored π. So it implies-Mrather than-MMπ. However, the dependence on the main input file gets left out π.SOURCE_DATE_EPOCHβ If this variable is set, its value specifies a UNIX timestamp to use in place of the current date and time in the"__DATE__"and"__TIME__"macros π°οΈ. That way the embedded timestamps stay 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, like the last modification time of the source or package, and the build process should set it π οΈ.
π SEE ALSO
gpl(7), gfdl(7), fsf-funding(7), gcc(1), and the Info entries for cpp and gcc ππ¦.
π COPYRIGHT
Copyright (c) 1987-2020 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 has 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 page, bestie! π«Άβ¨ Source: gcc-10, dated 2023-07-07, from CPP(1). You're officially a preprocessor expert now ππ π§
π¦ where this page comes from
- ubuntu noble: cpp-10-mipsisa64r6-linux-gnuabi64 10.5.0-4ubuntu2cross1
- π girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms