C ++ translation phase offset

Can someone explain why the following does not work?

int main() // Tried on several recent C++ '03 compilers. { #define FOO L const wchar_t* const foo = FOO"bar"; // Will error out with something like: "identifier 'L' is undefined." #undef FOO } 

I thought that preprocessing is done in an earlier translation phase than string literals and general token translation.

Will more or less the compiler see this:

 int main() { const wchar_t* const foo = L"bar"; } 

It would be great if someone could provide an explanation from the standard.

+4
source share
4 answers

Using:

 #define FOO L\ 

without a final \ will be a space between L and the macro substitution string. This is the result of g++ -E :

 const wchar_t* const foo = L "bar"; 
+6
source

As a variant of John's answer, I think you can define this as defined by Microsoft _T ():

 #define FOO(x) L ## x 

and use it as follows:

 FOO("bar") 

This will appropriately connect L to the text.

+1
source

The error message you get means that it pre-processes your #define before it does something else, it just does not know what it means (after replacing all FOO with L s, it looks for what L means and cannot understand it).

The compiler sees your second bit of code, it just does not know what L"bar" at this point means.

Are you sure that everything is defined and correctly included?

0
source

Look at the exit from the preprocessor (g ++ -E)

 # 1 "ttt.cc" # 1 "<built-in>" # 1 "<command-line>" # 1 "ttt.cc" int main() { const wchar_t *const foo = L "FOO"; } 

There will be a space after your L.

0
source

Source: https://habr.com/ru/post/1308200/


All Articles