Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C programming, make change at two location with one macro

struct Error
{
   MACRO(1, Connect);
   MACRO(2, Timeout);
};    

I need to define MACRO() in such way that the above code will generate the following code.

struct Error
{  
   static const int Connect = 1;
   static const int Timeout = 2;
   const char * const name[] = {"Connect", "Timeout"};
};

Is this possible or what is the alternative to get what I'm trying to do?

like image 266
Dinesh Avatar asked Apr 17 '14 13:04

Dinesh


People also ask

What is macro substitution in C?

Macro substitution is a mechanism that provides a string substitution. It can be achieved through "#deifne". It is used to replace the first part with the second part of the macro definition, before the execution of the program. The first object may be a function type or an object.

Can we change macro value in C?

You can't. Macros are expanded by the Preprocessor, which happens even before the code is compiled. It is a purely textual replacement. If you need to change something at runtime, just replace your macro with a real function call.

How #define works in C?

The #define creates a macro, which is the association of an identifier or parameterized identifier with a token string. After the macro is defined, the compiler can substitute the token string for each occurrence of the identifier in the source file.

What is AC macro?

Overview. Macro in C programming is known as the piece of code defined with the help of the #define directive. Macros in C are very useful at multiple places to replace the piece of code with a single value of the macro. Macros have multiple types and there are some predefined macros as well.


1 Answers

You can't do this directly, but you can if you move the macros to a separate location (such as a separate file):

macros.hpp

MACRO(1, Connect)
MACRO(2, Timeout)

#undef MACRO

the other file

struct Error
{
  #define MACRO(a, b) static const int b = a;
  #include "macros.hpp"

  const char * const name [] = {
  #define MACRO(a, b) #b,
  #include "macros.hpp"
  }
};

Alternatively, you could achieve a similar effect with Boost.Preprocessor.

like image 184
Angew is no longer proud of SO Avatar answered Sep 29 '22 07:09

Angew is no longer proud of SO