Line control
The miscellaneous preprocessing directives: #line rewrites the reported line number and file name, #error and #warning produce diagnostics on purpose, #pragma is left to the implementation, a lone # does nothing, and the _Pragma operator can be generated by macros.
Key points
#line 100 "x.y"makes subsequent__LINE__,__FILE__andstd::source_locationreport a presumed line number and file name, mainly so code generators can point back to the original file.#errormakes the program ill-formed;#warning(C++23) only requires the compiler to issue a diagnostic, and the program remains well-formed.- The effect of
#pragmais entirely implementation-defined and can make the implementation nonconforming; unrecognized pragmas are ignored, so a misspelling isn't an error. - Macros can't produce
#pragma, but they can produce_Pragma("...")._Pragmaremoves the string's quotes and the\"and\\escapes, then executes the result as a#pragma.
#line: rewriting the reported location [cpp.line]#
#include <source_location>
#line 100 "fake.cpp"
constexpr auto loc = std::source_location::current();
static_assert(loc.line() == 100); // the first line after #line is 100
#define N 200
#define F "other.cpp"
#line N F // macro replacement first, then processed as one of the first two forms
static_assert(__LINE__ == 200);
int main() {}Tools such as bison, flex and Qt's moc translate user-written .y, .l and similar files into .cpp, inserting #line into the generated code. That way compile errors and debug information point to lines in the original file rather than some line in the generated file.
#line changes the presumed line number and file name. __LINE__, __FILE__ ([cpp.predefined]) and std::source_location ([support.srcloc]) all report presumed locations, so they are all affected by it.
Three forms (¶3–¶5)#
¶3 # line digit-sequence causes subsequent source lines to be numbered as if starting from the given line number. The digits are interpreted as decimal, so #line 010 sets 10, not octal 8; Clang 23 warns about this in our tests. Values outside [1, 2147483647] are conditionally-supported: an implementation may support them, but if it doesn't, it must diagnose them. In C++23 and earlier this was undefined behavior.
¶4 # line digit-sequence "file-name" sets the line number and also changes the presumed source file name to the contents of the string.
¶5 For # line tokens... not matching either of the above forms, the tokens are first macro-replaced as in ordinary text. After replacement they must match one of the first two forms, or the program is ill-formed.
¶1 The file name must be a string literal with no prefix. #line 10 u8"x.cpp" is ill-formed; Clang 23 reports invalid filename for #line directive in our tests.
Definition of the line number (¶2)#
¶2 The line number of the current source line is one greater than the number of new-line characters read or introduced in translation phase 1 while processing the source file up to the current preprocessing token.
This sentence means two things. First, it counts physical lines: lines spliced with backslashes in phase 2 still each take a line number. Second, it looks at the line of the current token, so __LINE__ in a macro invocation spanning lines takes the line it's on:
#define ID(x) x
int a = ID(
__LINE__ // line 3: the result is 3, not line 2 where ID( is
);
int main() { return a == 3 ? 0 : 1; }LINE in a replacement list
After #define M() __LINE__, with M( on line 3 and ) on line 4, what does M() give? Whether the current preprocessing token here is the __LINE__ at the definition, the macro name or the closing parenthesis isn't specified in more detail. In our tests Clang 23 gives 4, the line of the closing parenthesis. Portable code shouldn't depend on the exact value of __LINE__ in invocations spanning lines.
Linemarkers in preprocessed output
The output of clang -E and gcc -E is full of lines like # 42 "file.cpp" 2, called linemarkers. They aren't #line: # followed directly by a number isn't any directive name, so by [cpp.pre]/3 it's a conditionally-supported directive with implementation-defined meaning. GCC and Clang use the trailing numeric flags to indicate entering a file, returning to a file, system headers and so on. The -P option turns off these lines.
#error and #warning [cpp.error]#
#if __cplusplus < 202002L
# error "requires C++20"
#endif
#ifndef NDEBUG
# warning "debug build: performance numbers aren't representative"
#endif
int main() {}¶1 #error makes the program ill-formed, and the compiler must reject it ([intro.compliance]). #warning only requires the implementation to issue at least one diagnostic for the translation unit; the program remains well-formed and translation continues. The program above compiles successfully in a default build while printing a warning.
¶2 Recommended practice: the diagnostic produced by either should include the preprocessing tokens written in the directive.
#warning was added in C++23 (P2437R1), in step with C23. GCC and Clang had long supported it as an extension.
The most common use of #error is to reject unsupported configurations in conditional compilation. It can only check what's known at preprocessing time, that is, macro values ([cpp.cond]); checking sizeof or type properties takes static_assert.
Apostrophes in the message
In #warning don't use this, the ' can't form a character literal with the following characters and can only become a token on its own. By [lex.pptoken]/1, a lone ' or " token makes the program ill-formed. So a directive meant only as a warning makes the program ill-formed. In our tests Clang 23 just prints the warning and compiles as usual; other implementations may reject it. Writing the message as a string literal avoids the problem: #warning "don't use this".
#pragma [cpp.pragma]#
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
int main() { int unused = 0; }
#pragma GCC diagnostic pop¶1 # pragma tokens... causes the implementation to behave in an implementation-defined manner. That behavior may cause translation to fail or cause the compiler or the resulting program to behave in a nonconforming manner. Pragmas not recognized by the implementation are ignored.
This gives implementations a great deal of freedom. #pragma pack changing a class's layout rules and #pragma GCC optimize("fast-math") relaxing floating-point semantics are both allowed by the standard. The only constraint the standard places on pragmas is that unrecognized ones be ignored.
- The C++ standard defines no pragmas. The C standard defines pragmas beginning with
STDC, such as#pragma STDC FP_CONTRACT, which C++ didn't adopt.#pragma onceisn't standard either ([cpp.include]). - Ignoring the unrecognized means a misspelled pragma isn't an error. GCC's and Clang's
-Wunknown-pragmas(part of-Wall) warns about it. - Tokens in a pragma aren't macro-replaced by default ([cpp.pre]/8), but an implementation may specify replacement for particular pragmas. For example, the OpenMP specification requires macro replacement of the tokens after
#pragma omp. - An unrecognized pragma is still a directive, so it's still ill-formed in a macro argument ([cpp.replace.general]/14).
Common pragmas
| Pragma | Effect | Supported by |
|---|---|---|
once |
prevents multiple inclusion | all major |
pack(push, n) / pack(pop) |
changes member alignment | all major |
GCC diagnostic push/pop/ignored |
turns warnings on and off locally | GCC, Clang |
clang diagnostic ... |
same | Clang |
warning(disable: 4996) |
same | MSVC |
push_macro("X") / pop_macro("X") |
saves and restores macro definitions | all major |
omp parallel for etc. |
OpenMP | with -fopenmp |
message("...") |
prints a message at compile time | all major |
The null directive [cpp.null]#
¶1 A line containing only a # has no effect.
#
# include <cstdio>
#
int main() {}Old code sometimes uses a lone # to visually separate blocks of directives, and code generators often produce null directives. It is the formal # new-line in the grammar of [cpp.pre], which is different from a conditionally-supported directive where # is followed by something that isn't a directive name.
The _Pragma operator [cpp.pragma.op]#
Why it's needed#
The result of macro expansion isn't treated as a directive ([cpp.rescan]/4), so macros can't produce #pragma. _Pragma is an operator, not a directive: it can appear in ordinary code and can be produced by macro expansion; it's executed in translation phase 4 with the same effect as a #pragma. It comes from C99 and was brought into C++11 (N1653).
#define DO_PRAGMA(x) _Pragma(#x)
#define DIAG_PUSH DO_PRAGMA(GCC diagnostic push)
#define DIAG_IGNORE(w) DO_PRAGMA(GCC diagnostic ignored w)
#define DIAG_POP DO_PRAGMA(GCC diagnostic pop)
DIAG_PUSH
DIAG_IGNORE("-Wunused-variable")
int main() { int unused = 0; }
DIAG_POPThe macros for locally disabling warnings in cross-platform libraries such as Boost, fmt and Abseil are almost all written this way. The string in DIAG_IGNORE("-Wunused-variable") becomes "GCC diagnostic ignored \"-Wunused-variable\"" through #x, and _Pragma restores it.
Destringizing (¶1)#
¶1 _Pragma ( string-literal ) is processed as follows:
- The string literal is destringized: delete the encoding prefix (if any) and the leading and trailing double quotes, replace each
\"with", and each\\with\. - The resulting sequence of characters is processed through translation phase 3 into preprocessing tokens, which are executed as if they were the tokens of a
#pragmadirective. - The original four tokens
_Pragma,(, the string literal and)are removed.
Only \" and \\ are processed; other escape sequences such as \n are left as two characters. This is exactly the inverse of # stringizing ([cpp.stringize]/2): stringizing adds \ before " and \ inside literals, and destringizing removes them. So _Pragma(#x) restores the tokens of x exactly.
The example in ¶2 shows this round trip:
#pragma listing on "..\listing.dir"
// is equivalent to
_Pragma ( "listing on \"..\\listing.dir\"" )
// the same effect when generated by macros:
#define LISTING(x) PRAGMA(listing on #x)
#define PRAGMA(x) _Pragma(#x)
LISTING( ..\listing.dir )LISTING( ..\listing.dir ) first gives PRAGMA(listing on "..\listing.dir"). When #x stringizes here, the \ is outside a literal and isn't escaped. PRAGMA's #x stringizes again, and this time "..\listing.dir" is a string literal whose " and \ must be escaped, giving "listing on \"..\\listing.dir\"". Finally _Pragma destringizes it, restoring listing on "..\listing.dir". In our tests Clang 23's -E outputs #pragma listing on "..\listing.dir".
_Pragma takes only one string literal
Adjacent string literals are concatenated in phase 6, while _Pragma is executed in phase 4, so _Pragma("GCC diagnostic " "push") doesn't work; Clang 23 reports _Pragma takes a parenthesized string literal in our tests. When concatenation is needed, stringize the whole pragma contents at once with # in a macro.
When _Pragma executes
In ordinary code, _Pragma executes when the preprocessor scans it; in the result of a macro expansion, it executes after complete replacement ([cpp.rescan]/4). In the replacement list of a #define, it is neither expanded nor executed until the macro is used. When _Pragma appears as a macro argument, whether it executes during the argument's pre-expansion or after the outer macro's complete replacement isn't specified in more detail, so where diagnostic pragmas take effect may not be as expected on different compilers. The safe approach is to write _Pragma directly in the macro's replacement list rather than passing it in as an argument.
History#
History
- C++98's
#line,#error,#pragmaand null directive were all the same as C89's. - C++11 brought in
_Pragmafrom C99 (N1653). - C++23 added
#warning(P2437R1). - Wording after C++23 changed
#linevalues outside [1, 2147483647] from undefined behavior to conditionally-supported, and precisely defined the line number as the physical line number up to the current preprocessing token.
Questions#
Question 1
#define STR(x) #x
#define P(x) _Pragma(STR(x))
P(message("hi"))#define P(x) _Pragma(#x)?
Answer
It works, and here the two forms give the same result. P's parameter x isn't the operand of #, so the argument message("hi") is first fully expanded (no change), and substitution gives _Pragma(STR(message("hi"))). On rescanning, STR(...) expands to "message(\"hi\")", and _Pragma executes after complete replacement, destringizing to message("hi").
There is a difference when the argument contains macros. With #define MSG "hi", P(message(MSG)) stringizes indirectly through STR, so MSG is expanded first and the pragma receives message("hi"); _Pragma(#x) stringizes directly, and the pragma receives message(MSG). Whether the pragma itself expands MSG further is up to the implementation. Clang's #pragma message happens to expand its argument, so in our tests Clang 23 prints hi for both forms; for a pragma that doesn't expand its arguments, the two would differ.
Question 2
Is #line 0 valid? #line 2147483648? #line 0x10?
Answer
The numbers in #line 0 and #line 2147483648 are both outside [1, 2147483647], so by ¶3 they're conditionally-supported: an implementation may support them, and must diagnose them if it doesn't. In our tests Clang 23 accepts both, giving a -Wgnu-zero-line-directive warning for the former and a -Wpedantic warning for the latter.
The 0x10 in #line 0x10 isn't a digit sequence and doesn't match the forms of ¶3 or ¶4; after macro replacement per ¶5 it still doesn't match, so it's ill-formed. In our tests Clang 23 reports the error #line directive requires a simple digit sequence.