Using the C preprocessor to determine the current area?

I am developing an application in C / Objective-C (No C ++, please, I already have a solution), and I came across an interesting use case.

Since clang does not support nested functions, my original approach will not work:

#define CREATE_STATIC_VAR(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }

This code will compile with GCC, but since clang does not support nested functions, I get a compilation error:

Expected ';' at the end of the ad.

So, I found a solution that works for Clang for variables inside a function:

#define CREATE_STATIC_VAR_LOCAL(Type, Name, Dflt) static Type Name; ^{ /* loading code here */ }(); // anonymous block usage

However, I was wondering if there is a way to use the macro link to select the appropriate one for the situation, for example:

#define CREATE_STATIC_VAR_GLOBAL(Type, Name, Dflt) static Type Name; __attribute__((constructor)) void static_ ## Type ## _ ## Name ## _init_var(void) { /* loading code here */ }
#define CREATE_STATIC_VAR_LOCAL(Type, Name, Dflt) static Type Name; ^{ /* loading code here */ }(); // anonymous block usage

#define SCOPE_CHOOSER LOCAL || GLOBAL
#define CREATE_STATIC_VAR(Type, Name, DFLT) CREATE_STATIC_VAR_ ## SCOPE_CHOOSER(Type, Name, Dflt)

Obviously, the final implementation does not have to be that way, but something like that will be enough.

__builtin_constant_p __func__, __func__ , .

__builtin_choose_expr, .

- ? , - , , .

.. , CREATE_STATIC_VAR_GLOBAL CREATE_STATIC_VAR_LOCAL , , . , ++ , .

+5
1
#define SCOPE_CHOOSER LOCAL || GLOBAL
#define CREATE_STATIC_VAR(Type, Name, DFLT) CREATE_STATIC_VAR_ ## SCOPE_CHOOSER(Type, Name, Dflt)

, C , , , SCOPE_CHOOSER, , , ,

CREATE_STATIC_VAR_LOCAL || GLOBAL(Type, Name, Dflt);

"-" ; , "", - #if. ( ) - , , .

? , __attribute__((constructor)), , , ... __attribute__((constructor)), ... . , , , , - .

EDIT: , , , , 0 1 .

#define AT_GLOBAL_SCOPE __builtin_types_compatible_p(const char (*)[1], __typeof__(&__func__))

, "", "". , .

+1

All Articles