Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can #if conditional areas cross include file boundaries?

In the MSDN (https://msdn.microsoft.com/en-us/library/ew2hz0yd.aspx) I see the following:

All conditional-compilation directives, such as #if and #ifdef, must be matched with closing #endif directives prior to the end of file; otherwise, an error message is generated. When conditional-compilation directives are contained in include files, they must satisfy the same conditions: There must be no unmatched conditional-compilation directives at the end of the include file.

Well, simple and clear. A the same time I cannot find something like that in the C++11 standard. My question is this legal limitation?

I fully understand that splitting conditional compilation over several #include layers is not a good idea and should be avoided.

Does anybody know how other compilers (GCC, CLANG) handle this case? Maybe this was discussed somewhere?

like image 847
Kirill Kobelev Avatar asked Feb 28 '16 22:02

Kirill Kobelev


People also ask

Can be means?

—used to say that what a person does or feels is understandable or that a person should not be blamed for doing or feeling something.

How is can use?

Can, like could and would, is used to ask a polite question, but can is only used to ask permission to do or say something ("Can I borrow your car?" "Can I get you something to drink?").

CAN is noun or verb?

can (noun) can (verb) can–do (adjective) canned (adjective)

Can grammar rules?

Auxiliary verb can (positive) - can't (negative) useUse 'can' to talk about possibility. Always use can with another verb. I can = I know to do something. / I know that something is possible for me. Future: Use can if you are deciding now what to do in the future.


1 Answers

#if FOO
#include "hashif.h"


extern "C" int printf(const char* fmt, ...);

int main()
{
    printf("Hello, World\n");
}

and hashif.h contains this:

#define BAR 1
#else
#define BAR 2
#endif

then clang++ gives an error.

hashif.cpp:1:2: error: unterminated conditional directive
#if FOO  
^
1 error generated.

Edit: And g++ and cpp all behave the same way.

Exact output from:

$ cpp hashif.cpp -DFOO=1
# 1 "hashif.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "hashif.cpp"

# 1 "hashif.h" 1
In file included from hashif.cpp:2:0:
hashif.h:2:2: error: #else without #if
 #else
  ^
hashif.h:3:0: warning: "BAR" redefined
 #define BAR 2
 ^
hashif.h:1:0: note: this is the location of the previous definition
 #define BAR 1
 ^
hashif.h:4:2: error: #endif without #if
 #endif
  ^
# 3 "hashif.cpp" 2


extern "C" int printf(const char* fmt, ...);

int main()
{
    printf("Hello, World\n");
hashif.cpp:1:0: error: unterminated #if
 #if FOO
 ^
}
like image 187
Mats Petersson Avatar answered Sep 30 '22 03:09

Mats Petersson