Contents 1 Phases 1.1 Including files 1.2 Conditional compilation 1.3 Macro definition and expansion 1.4 Special macros and directives 1.4.1 Token stringification 1.4.2 Token concatenation 1.5 User-defined compilation errors 2 Implementations 2.1 Compiler-specific preprocessor features 3 Other uses 4 See also 5 References 6 External links


Phases[edit] Preprocessing is defined by the first four (of eight) phases of translation specified in the C Standard. Trigraph replacement: The preprocessor replaces trigraph sequences with the characters they represent. Line splicing: Physical source lines that are continued with escaped newline sequences are spliced to form logical lines. Tokenization: The preprocessor breaks the result into preprocessing tokens and whitespace. It replaces comments with whitespace. Macro expansion and directive handling: Preprocessing directive lines, including file inclusion and conditional compilation, are executed. The preprocessor simultaneously expands macros and, in the 1999 version of the C standard,[clarification needed] handles _Pragma operators. Including files[edit] One of the most common uses of the preprocessor is to include another file: #include <stdio.h> int main(void) { printf("Hello, world!\n"); return 0; } The preprocessor replaces the line #include <stdio.h> with the text of the file 'stdio.h', which declares the printf() function among other things. This can also be written using double quotes, e.g. #include "stdio.h". If the filename is enclosed within angle brackets, the file is searched for in the standard compiler include paths. If the filename is enclosed within double quotes, the search path is expanded to include the current source directory. C compilers and programming environments all have a facility which allows the programmer to define where include files can be found. This can be introduced through a command line flag, which can be parameterized using a makefile, so that a different set of include files can be swapped in for different operating systems, for instance. By convention, include files are given a .h extension, and files not included by others are given a .c extension. However, there is no requirement that this be observed. Files with a .def extension may denote files designed to be included multiple times, each time expanding the same repetitive content; #include "icon.xbm" is likely to refer to an XBM image file (which is at the same time a C source file). #include often compels the use of #include guards or #pragma once to prevent double inclusion. Conditional compilation[edit] The if-else directives #if, #ifdef, #ifndef, #else, #elif and #endif can be used for conditional compilation. #if VERBOSE >= 2 print("trace message"); #endif Most compilers targeting Microsoft Windows implicitly define _WIN32.[1] This allows code, including preprocessor commands, to compile only when targeting Windows systems. A few compilers define WIN32 instead. For such compilers that do not implicitly define the _WIN32 macro, it can be specified on the compiler's command line, using -D_WIN32. #ifdef __unix__ /* __unix__ is usually defined by compilers targeting Unix systems */ # include <unistd.h> #elif defined _WIN32 /* _WIN32 is usually defined by compilers targeting 32 or 64 bit Windows systems */ # include <windows.h> #endif The example code tests if a macro __unix__ is defined. If it is, the file <unistd.h> is then included. Otherwise, it tests if a macro _WIN32 is defined instead. If it is, the file <windows.h> is then included. A more complex #if example can use operators, for example something like: #if !(defined __LP64__ || defined __LLP64__) || defined _WIN32 && !defined _WIN64 // we are compiling for a 32-bit system #else // we are compiling for a 64-bit system #endif Translation can also be caused to fail by using the #error directive: #if RUBY_VERSION == 190 # error 1.9.0 not supported #endif Macro definition and expansion[edit] There are two types of macros, object-like and function-like. Object-like macros do not take parameters; function-like macros do (although the list of parameters may be empty). The generic syntax for declaring an identifier as a macro of each type is, respectively: #define <identifier> <replacement token list> // object-like macro #define <identifier>(<parameter list>) <replacement token list> // function-like macro, note parameters The function-like macro declaration must not have any whitespace between the identifier and the first, opening, parenthesis. If whitespace is present, the macro will be interpreted as object-like with everything starting from the first parenthesis added to the token list. A macro definition can be removed with #undef: #undef <identifier> // delete the macro Whenever the identifier appears in the source code it is replaced with the replacement token list, which can be empty. For an identifier declared to be a function-like macro, it is only replaced when the following token is also a left parenthesis that begins the argument list of the macro invocation. The exact procedure followed for expansion of function-like macros with arguments is subtle. Object-like macros were conventionally used as part of good programming practice to create symbolic names for constants, e.g., #define PI 3.14159 instead of hard-coding numbers throughout the code. An alternative in both C and C++, especially in situations in which a pointer to the number is required, is to apply the const qualifier to a global variable. This causes the value to be stored in memory, instead of being substituted by the preprocessor. An example of a function-like macro is: #define RADTODEG(x) ((x) * 57.29578) This defines a radians-to-degrees conversion which can be inserted in the code where required, i.e., RADTODEG(34). This is expanded in-place, so that repeated multiplication by the constant is not shown throughout the code. The macro here is written as all uppercase to emphasize that it is a macro, not a compiled function. The second x is enclosed in its own pair of parentheses to avoid the possibility of incorrect order of operations when it is an expression instead of a single value. For example, the expression RADTODEG(r + 1) expands correctly as ((r + 1) * 57.29578); without parentheses, (r + 1 * 57.29578) gives precedence to the multiplication. Similarly, the outer pair of parentheses maintain correct order of operation. For example, 1 / RADTODEG(r) expands to 1 / ((r) * 57.29578); without parentheses, 1 / (r) * 57.29578 gives precedence to the division. Special macros and directives[edit] Certain symbols are required to be defined by an implementation during preprocessing. These include __FILE__ and __LINE__, predefined by the preprocessor itself, which expand into the current file and line number. For instance the following: // debugging macros so we can pin down message origin at a glance // is bad #define WHERESTR "[file %s, line %d]: " #define WHEREARG __FILE__, __LINE__ #define DEBUGPRINT2(...) fprintf(stderr, __VA_ARGS__) #define DEBUGPRINT(_fmt, ...) DEBUGPRINT2(WHERESTR _fmt, WHEREARG, __VA_ARGS__) // OR // is good #define DEBUGPRINT(_fmt, ...) fprintf(stderr, "[file %s, line %d]: \t" _fmt, __FILE__, __LINE__, __VA_ARGS__) DEBUGPRINT("hey, x=%d\n", x); prints the value of x, preceded by the file and line number to the error stream, allowing quick access to which line the message was produced on. Note that the WHERESTR argument is concatenated with the string following it. The values of __FILE__ and __LINE__ can be manipulated with the #line directive. The #line directive determines the line number and the file name of the line below. E.g.: #line 314 "pi.c" printf("line=%d file=%s\n", __LINE__, __FILE__); generates the printf function: printf("line=%d file=%s\n", 314, "pi.c"); Source code debuggers refer also to the source position defined with __FILE__ and __LINE__. This allows source code debugging, when C is used as target language of a compiler, for a totally different language. The first C Standard specified that the macro __STDC__ be defined to 1 if the implementation conforms to the ISO Standard and 0 otherwise, and the macro __STDC_VERSION__ defined as a numeric literal specifying the version of the Standard supported by the implementation. Standard C++ compilers support the __cplusplus macro. Compilers running in non-standard mode must not set these macros, or must define others to signal the differences. Other Standard macros include __DATE__, the current date, and __TIME__, the current time. The second edition of the C Standard, C99, added support for __func__, which contains the name of the function definition within which it is contained, but because the preprocessor is agnostic to the grammar of C, this must be done in the compiler itself using a variable local to the function. Macros that can take a varying number of arguments (variadic macros) are not allowed in C89, but were introduced by a number of compilers and standardised in C99. Variadic macros are particularly useful when writing wrappers to functions taking a variable number of parameters, such as printf, for example when logging warnings and errors. One little-known usage pattern of the C preprocessor is known as X-Macros.[2][3][4] An X-Macro is a header file. Commonly these use the extension ".def" instead of the traditional ".h". This file contains a list of similar macro calls, which can be referred to as "component macros". The include file is then referenced repeatedly. Many compilers define additional, non-standard macros, although these are often poorly documented. A common reference for these macros is the Pre-defined C/C++ Compiler Macros project, which lists "various pre-defined compiler macros that can be used to identify standards, compilers, operating systems, hardware architectures, and even basic run-time libraries at compile-time". Token stringification[edit] The # operator (known as the "Stringification Operator") converts a token into a string, escaping any quotes or backslashes appropriately. Example: #define str(s) #s str(p = "foo\n";) // outputs "p = \"foo\\n\";" str(\n) // outputs "\n" If you want to stringify the expansion of a macro argument, you have to use two levels of macros: #define xstr(s) str(s) #define str(s) #s #define foo 4 str (foo) // outputs "foo" xstr (foo) // outputs "4" You cannot combine a macro argument with additional text and stringify it all together. You can however write a series of adjacent string constants and stringified arguments: the C compiler will then combine all the adjacent string constants into one long string. Token concatenation[edit] The ## operator (known as the "Token Pasting Operator") concatenates two tokens into one token. Example: #define DECLARE_STRUCT_TYPE(name) typedef struct name##_s name##_t DECLARE_STRUCT_TYPE(g_object); // Outputs: typedef struct g_object_s g_object_t; User-defined compilation errors[edit] The #error directive outputs a message through the error stream. #error "error message"


Implementations[edit] All C, C++ and Objective-C implementations provide a preprocessor, as preprocessing is a required step for those languages, and its behavior is described by official standards for these languages, such as the ISO C standard. Implementations may provide their own extensions and deviations, and vary in their degree of compliance with written standards. Their exact behavior may depend on command-line flags supplied on invocation. For instance, the GNU C preprocessor can be made more standards compliant by supplying certain flags.[5] Compiler-specific preprocessor features[edit] The #pragma directive is a compiler-specific directive, which compiler vendors may use for their own purposes. For instance, a #pragma is often used to allow suppression of specific error messages, manage heap and stack debugging and so on. A compiler with support for the OpenMP parallelization library can automatically parallelize a for loop with #pragma omp parallel for. C99 introduced a few standard #pragma directives, taking the form #pragma STDC ..., which are used to control the floating-point implementation. Many implementations do not support trigraphs or do not replace them by default. Many implementations (including, e.g., the C compilers by GNU, Intel, Microsoft and IBM) provide a non-standard directive to print out a warning message in the output, but not stop the compilation process. A typical use is to warn about the usage of some old code, which is now deprecated and only included for compatibility reasons, e.g.: (GNU, Intel and IBM) #warning "Do not use ABC, which is deprecated. Use XYZ instead." (Microsoft) #pragma message("Do not use ABC, which is deprecated. Use XYZ instead.") Some Unix preprocessors traditionally provided "assertions", which have little similarity to assertions used in programming.[6] GCC provides #include_next for chaining headers of the same name.[7] Objective-C preprocessors have #import, which is like #include but only includes the file once.


Other uses[edit] As the C preprocessor can be invoked separately from the compiler with which it is supplied, it can be used separately, on different languages. Notable examples include its use in the now-deprecated imake system and for preprocessing Fortran. However, such use as a general purpose preprocessor is limited: the input language must be sufficiently C-like.[5] For preprocessing Fortran, a more flexible variant of the C preprocessor is preferred, GPP.[8] The GNU Fortran compiler automatically calls gpp before compiling Fortran code if certain file extensions are used.[9] Intel offers a Fortran preprocessor, fpp, for use with the ifort compiler, which has similar capabilities.[10] GPP also works acceptably with most assembly languages. GNU mentions assembly as one of the target languages among C, C++ and Objective-C in the documentation of its implementation of the preprocessor. This requires that the assembler syntax not conflict with GPP syntax, which means no lines starting with # and that double quotes, which gpp interprets as string literals and thus ignores, don't have syntactical meaning other than that. The C preprocessor is not Turing-complete, but it comes very close: recursive computations can be specified, but with a fixed upper bound on the amount of recursion performed.[11] However, the C preprocessor is not designed to be, nor does it perform well as, a general-purpose programming language. As the C preprocessor does not have features of some other preprocessors, such as recursive macros, selective expansion according to quoting, and string evaluation in conditionals, it is very limited in comparison to a more general macro processor such as m4.


See also[edit] C syntax Make Preprocessor m4 (computer language) PL/I preprocessor


References[edit] ^ List of predefined ANSI C and Microsoft C++ implementation macros. ^ Wirzenius, Lars. C "Preprocessor Trick For Implementing Similar Data Types". Retrieved January 9, 2011 ^ Meyers, Randy (May 2001). "The New C: X Macros". Dr. Dobb's Journal. Retrieved 1 May 2008.  ^ Beal, Stephan (August 2004). "Supermacros". Retrieved 27 October 2008.  ^ a b "The C Preprocessor: Overview". Retrieved 17 July 2016.  ^ GCC Obsolete features ^ https://gcc.gnu.org/onlinedocs/cpp/Wrapper-Headers.html ^ "GPP 2.23 — Generic Preprocessor". Retrieved 17 July 2016.  ^ "1.3 Preprocessing and conditional compilation". gnu.org.  ^ "Using the fpp Preprocessor". Intel. Retrieved 14 October 2015.  ^ "Is the C99 preprocessor Turing complete?". 


External links[edit] Wikibooks has a book on the topic of: C Programming/Preprocessor ISO/IEC 9899. The official C standard. As of 2014, the latest publicly available version is a working paper for C11. GNU CPP online manual Visual Studio .NET preprocessor reference Pre-defined C/C++ Compiler Macros project: lists "various pre-defined compiler macros that can be used to identify standards, compilers, operating systems, hardware architectures, and even basic run-time libraries at compile-time" v t e C programming language ANSI C C89 and C90 C99 C11 Embedded C MISRA C Features Functions Header files Libraries Operators String Syntax Preprocessor Data types Standard library functions Char (ctype.h) File I/O (stdio.h) Math (math.h) Dynamic memory (stdlib.h) String (string.h) Time (time.h) Variadic (stdarg.h) POSIX Standard libraries Bionic libhybris dietlibc EGLIBC glibc klibc Microsoft Run-time Library musl Newlib uClibc BSD libc Compilers Comparison of compilers ACK Borland Turbo C Clang GCC ICC LCC Pelles C PCC SDCC TCC Microsoft Visual Studio / Express / C++ Watcom C/C++ IDEs Comparison of IDEs Anjuta Code::Blocks CodeLite Eclipse Geany Microsoft Visual Studio NetBeans Comparison with other languages Compatibility of C and C++ Comparison with Embedded C Comparison with Pascal Comparison of programming languages Descendant languages C++ C# D Objective-C Alef Limbo Go Vala Category Retrieved from "https://en.wikipedia.org/w/index.php?title=C_preprocessor&oldid=809043346" Categories: C (programming language)Transformation languagesMacro programming languagesHidden categories: Use dmy dates from July 2013Wikipedia articles needing style editing from February 2013All articles needing style editingArticles lacking in-text citations from March 2015All articles lacking in-text citationsArticles with multiple maintenance issuesWikipedia articles needing clarification from March 2016


Navigation menu Personal tools Not logged inTalkContributionsCreate accountLog in Namespaces ArticleTalk Variants Views ReadEditView history More Search Navigation Main pageContentsFeatured contentCurrent eventsRandom articleDonate to WikipediaWikipedia store Interaction HelpAbout WikipediaCommunity portalRecent changesContact page Tools What links hereRelated changesUpload fileSpecial pagesPermanent linkPage informationWikidata itemCite this page Print/export Create a bookDownload as PDFPrintable version In other projects Wikibooks Languages ČeštinaDeutschEspañolFrançais한국어LatinaMagyarPolskiРусскийSuomiTürkçeУкраїнська中文 Edit links This page was last edited on 6 November 2017, at 20:11. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Privacy policy About Wikipedia Disclaimers Contact Wikipedia Developers Cookie statement Mobile view (window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgPageParseReport":{"limitreport":{"cputime":"0.228","walltime":"0.354","ppvisitednodes":{"value":1451,"limit":1000000},"ppgeneratednodes":{"value":0,"limit":1500000},"postexpandincludesize":{"value":51353,"limit":2097152},"templateargumentsize":{"value":7303,"limit":2097152},"expansiondepth":{"value":16,"limit":40},"expensivefunctioncount":{"value":4,"limit":500},"entityaccesscount":{"value":0,"limit":400},"timingprofile":["100.00% 294.855 1 -total"," 30.88% 91.054 1 Template:Reflist"," 27.85% 82.107 3 Template:Ambox"," 21.35% 62.952 1 Template:Multiple_issues"," 20.34% 59.974 2 Template:Cite_journal"," 12.00% 35.378 1 Template:Use_dmy_dates"," 10.11% 29.796 1 Template:Clarify"," 9.05% 26.681 1 Template:Fix-span"," 9.05% 26.677 1 Template:CProLang"," 7.13% 21.025 1 Template:Navbox"]},"scribunto":{"limitreport-timeusage":{"value":"0.090","limit":"10.000"},"limitreport-memusage":{"value":4125231,"limit":52428800}},"cachereport":{"origin":"mw1262","timestamp":"20180217150147","ttl":1900800,"transientcontent":false}}});});(window.RLQ=window.RLQ||[]).push(function(){mw.config.set({"wgBackendResponseTime":219,"wgHostname":"mw1238"});});


C_preprocessor - Photos and All Basic Informations

C_preprocessor More Links

Talk:C PreprocessorHelp:Maintenance Template RemovalWikipedia:What Wikipedia Is NotWikipedia:Neutral Point Of ViewHelp:Maintenance Template RemovalWikipedia:Citing SourcesWikipedia:Citing SourcesWikipedia:WikiProject Fact And Reference CheckWikipedia:When To CiteHelp:Maintenance Template RemovalHelp:Maintenance Template RemovalPreprocessorC (programming Language)C++Programming LanguageHeader FilesMacro (computer Science)Conditional CompilationComputer ProgramCompilerTranslator (computing)Directive (programming)Text FilesC TrigraphEscape CharacterNewlineWhitespace CharacterWikipedia:Please ClarifySubroutineMake (software)X BitMapInclude GuardPragma OnceIf ElseConditional CompilationMicrosoft WindowsHard CodingRadianOrder Of OperationsDebuggerANSI CC99Variadic MacroC99PrintfX MacroHeader FileCompiler DirectiveOpenMPDeprecatedUnixAssertion (computing)Objective-CImakeFortranGeneral Purpose PreprocessorGNU FortranIntel Fortran CompilerAssembly LanguageString LiteralTuring CompletenessM4 (computer Language)C SyntaxMake (software)PreprocessorM4 (computer Language)PL/I PreprocessorTemplate:C Programming LanguageTemplate Talk:C Programming LanguageC (programming Language)ANSI CANSI CC99C11 (C Standard Revision)Embedded CMISRA CSubroutineInclude DirectiveCategory:C LibrariesOperators In C And C++C String HandlingC SyntaxC Data TypesC Standard LibraryC Character ClassificationC File Input/outputC Mathematical FunctionsC Dynamic Memory AllocationC String HandlingC Date And Time FunctionsStdarg.hC POSIX LibraryCategory:C Standard LibraryBionic (software)Hybris (software)DietlibcEmbedded GLIBCGNU C LibraryKlibcMicrosoft Windows Library FilesMuslNewlibUClibcBSD LibcCategory:C CompilersList Of CompilersAmsterdam Compiler KitBorland Turbo CClangGNU Compiler CollectionIntel C++ CompilerLCC (compiler)Pelles CPortable C CompilerSmall Device C CompilerTiny C CompilerMicrosoft Visual StudioMicrosoft Visual Studio ExpressVisual C++Watcom C/C++Category:Integrated Development EnvironmentsComparison Of Integrated Development EnvironmentsAnjutaCode::BlocksCodeLiteEclipse (software)GeanyMicrosoft Visual StudioNetBeansCategory:Comparison Of Individual Programming LanguagesCompatibility Of C And C++Embedded CComparison Of Pascal And CComparison Of Programming LanguagesC++C Sharp (programming Language)D (programming Language)Objective-CAlef (programming Language)Limbo (programming Language)Go (programming Language)Vala (programming Language)Category:C (programming Language)Help:CategoryCategory:C (programming Language)Category:Transformation LanguagesCategory:Macro Programming LanguagesCategory:Use Dmy Dates From July 2013Category:Wikipedia Articles Needing Style Editing From February 2013Category:All Articles Needing Style EditingCategory:Articles Lacking In-text Citations From March 2015Category:All Articles Lacking In-text CitationsCategory:Articles With Multiple Maintenance IssuesCategory:Wikipedia Articles Needing Clarification From March 2016Discussion About Edits From This IP Address [n]A List Of Edits Made From This IP Address [y]View The Content Page [c]Discussion About The Content Page [t]Edit This Page [e]Visit The Main Page [z]Guides To Browsing WikipediaFeatured Content – The Best Of WikipediaFind Background Information On Current EventsLoad A Random Article [x]Guidance On How To Use And Edit WikipediaFind Out About WikipediaAbout The Project, What You Can Do, Where To Find ThingsA List Of Recent Changes In The Wiki [r]List Of All English Wikipedia Pages Containing Links To This Page [j]Recent Changes In Pages Linked From This Page [k]Upload Files [u]A List Of All Special Pages [q]Wikipedia:AboutWikipedia:General Disclaimer



view link view link view link view link view link