Reputation: 13614
struct info _info;
#define INIT(a, b, c, d) \
struct info _info = {a, b, c, d}
This worked in C, but with the g++ I get:
error: redefinition of ‘info _info’
INIT
isn't always called, sometimes _info gets initialised some other way so that's why both ways have to stick around.
Context:
I'm using INIT in a file that is getting compiled with g++, but I also use it in files compiled by gcc. So the problem is: I need this headerfile code to work in both languages, regardless of whether I use the header in a c library or in a c++ library.
Kerrek pointed out I could use #ifdef, so I did this:
#ifndef __cplusplus
struct info _info;
#define INFO(a, b, c, d) \
struct info _info = {a, b, c, d}
#else
struct info _info;
#define INFO(a, b, c, d) \
_info = {a, b, c, d}
#endif
But it still won't work, I'm getting a error: ‘_info’ does not name a type
at the line I'm using the macro in my cpp project:
INFO("Information", 2 ,"again", 4)
Upvotes: 2
Views: 3771
Reputation: 8717
If memory serves me correctly you can use a typedef
and avoid the __cplusplus
specific section.
typedef struct taginfo { int x, y, z, w; } info;
info _info;
#define INFO(a,b,c,d) _info = {(a), (b), (c), (d)}
...and this should work in both C and C++.
See Why should we typedef a struct so often in C?
Upvotes: 0
Reputation: 476950
In C++, you don't say struct
in the variable declaration. The following should work:
struct info { int x, y, z, w; }; // type definition (elsewhere in your code)
#define INIT(a, b, c, d) info _info = {a, b, c, d}
INIT(1,2,3,4);
Because the variable name is fixed, this macro can only be used once inside any given scope, which is not obvious. For more flexibility, I'd add the variable name to the macro:
#define DECLARE_AND_INIT(var, a, b, c, d) info var = {a, b, c, d}
DECLARE_AND_INIT(my_info, 4, 5, 6, 7);
Upvotes: 3