Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preprocessor counter macro

Is there a way to create a COUNTER() macro (which follows the C++11/14 standard) that is expanded to a number which increases by one every time COUNTER() is invoked?

I've thought about it, but couldn't find a way to make it work. I didn't find a way to store "state" in the COUNTER() macro.

Example:

#define COUNTER() <...> // Implementation goes here...
#define UNIQUE_NAME_1() TEST ## COUNTER()
#define UNIQUE_NAME_2() TEST ## COUNTER()

// Note how the COUNTER() macro can be used with other macros
// (it cannot be implemented with C++ code)

int main() {
    std::cout << STRINGIFY(UNIQUE_NAME_1()) << std::endl;
    std::cout << STRINGIFY(UNIQUE_NAME_2()) << std::endl;
}

Expected output:

TEST0 
TEST1    
like image 445
Vittorio Romeo Avatar asked Mar 11 '14 17:03

Vittorio Romeo


People also ask

What is __ Size_type __?

Note that __SIZE_TYPE__ isn't a variable; it's a type. Compilers other than GCC probably do not provide it, unless they're trying to be compatible with GCC. If you want size_t , include <stddef. h> if you aren't including any of the other headers (such as <stdio. h> , <string.

Are macros removed after preprocessing?

Explanation: True, After preprocessing all the macro in the program are removed.

What are the most common predefined macros in C?

Predefined Macros in C99 standard: This macro gives value similar to __STDC_VERSION__, in that it expands to a version number. __OBJC__ Macro:: __OBJC__ Macro has value 1 if the Objective-C compiler is in use. __OBJC__ is used to test whether a header is compiled by a C compiler or an Objective-C compiler.

Is GCC macro?

The gcc option -D NAME defines a preprocessor macro NAME from the command line. If the program above is compiled with the command-line option -DTEST , the macro TEST will be defined and the resulting executable will print both messages: $ gcc -Wall -DTEST dtest.


1 Answers

GCC, and (I believe) VC++ both provide the __COUNTER__ macro, which does about what you'd expect. I don't know that it follows the standard exactly, but it's probably close enough for real-world use.

like image 122
Michael Kohne Avatar answered Oct 25 '22 08:10

Michael Kohne