What is the difference between #define WITHBRACKETS (1) and #define WITHBRACKETS 1?
I have macros defined in two places with same name (I know it's a bad thing that likely results in a redefinition warning) but they are defined differently.
So when I compile the code base, why does the compiler say, #define WITHBRACKETS (1) is an incompatible redefinition of #define WITHBRACKETS 1?
The preprocessor complains it's an incompatible redefinition because it is!
A macro is a token that the preprocessor replaces by a sequence of 0 or more other tokens whenever it encounters it.
#define WITHBRACKETS 1 Will define a token that will be replaced by a single other token.
#define WITHBRACKETS (1) Will define a token to be replaced by three other tokens.
Those aren't compatible things. The preprocessor doesn't know or care that their semantic meaning in the source is the same. All it cares about is the sequence of tokens.
It's a good idea to add the brackets sometimes, for example with something like this :
#define EXAMPLE (1 + 2)
the brackets here can be useful against operator priority errors ...
In your example, the compiler says there is a redefinition because the preprocessor does not know that 1 is the same as (1), it just sees that there are two different sequences of characters.
In simple words: Macros are merely about textual replacement.
If you have those two macros:
#define WITH (1)
#define WITHOUT 1
Then this:
foo( WITHOUT );
foo WITH ;
will expand to
foo( 1 );
foo (1);
So the two defines are indeed different. You can use the -E flag on gcc to see the output after the preprocessing.
PS: Dont use macros (if you dont need to ;).
Related
Imagine I have some "assert like" functionality, which declares a macro one way if a specific macro is defined, and a different way if it is not:
// in some header assert2.hpp
#ifdef NO_ASSERT2
#define assert2(x)
#else
#define assert2(x) assert2_handler(x);
#endif
Here, the NO_ASSERT2 macro is very much like the NDEBUG macro in standard assert(3).
What I'd like to do, however is allow the user to override the NO_ASSERT2 check with their own macro, before including the file. E.g., if you included assert2.hpp like this:
#define NO_ASSERT_KEY NO_ASSERT_CUSTOM
#include "assert2.hpp"
Then the macro NO_ASSERT_CUSTOM would be checked instead of the default NO_ASSERT2 for this translation unit.
It doesn't have to work exactly like the above - I just need some way to override the behavior on a per-file basis, without needing more than the 1 line of boilerplate shown above at the location of the include.
This isn't pretty... but this approach may work for you. It assumes that the macro is defined using either #define FOO, #define FOO 1, or -DFOO (assuming as typical that this creates something equivalent to #define FOO 1).
#define SECOND(...) SECOND_I(__VA_ARGS__,,)
#define SECOND_I(A,B,...) B
#define GLUE3(A,B,C) GLUE3_I(A,B,C)
#define GLUE3_I(A,B,C) A##B##C
#define AGLUE3(A,B,C) AGLUE3_I(A,B,C)
#define AGLUE3_I(A,B,C) A##B##C
#define TEST_ASSERT_KEY GLUE3(NO_ASSERT_PROBE,0_,NO_ASSERT_KEY)
#define NO_ASSERT_PROBE0_NO_ASSERT_KEY AGLUE3(NO_ASSERT_PROBE,0_,NO_ASSERT2)
#define NO_ASSERT_PROBE0_ ,1
#define NO_ASSERT_PROBE0_1 ,1
#define NO_ASSERT_TEST SECOND(TEST_ASSERT_KEY,0)
With this, your usage would be:
#if NO_ASSERT_TEST
#define assert2(x)
#else
#define assert2(x) assert2_handler(x);
#endif
Here's a demo at stacked-crooked.
This uses pattern matching in the preprocessor via the indirect SECOND macro. The idea is that it expands to its second argument, but only indirectly... this allows you to construct as the first argument a pattern. Usually that first argument's ignored, but if you want to match something you can set it up to where the first argument would be a macro that expands with a comma; that shifts a new second argument in, replacing the default.
From here it's easier to explain backwards. NO_ASSERT_TEST uses TEST_ASSERT_KEY to construct a pattern with a default of 0. TEST_ASSERT_KEY builds NO_ASSERT_PROBE0_ concatenated with NO_ASSERT_KEY. When NO_ASSERT_KEY is defined, this would build NO_ASSERT_PROBE0_ concatenated with the expansion of what it's defined as. Otherwise it rebuilds the test token using NO_ASSERT_PROBE0_ concatenated with NO_ASSERT2.
Either way this is an indirect paste, so NO_ASSERT_KEY in the former case or NO_ASSERT2 in the latter is expanded first. In the former case, if say NO_ASSERT_KEY is NO_ASSERT_CUSTOM and NO_ASSERT_CUSTOM is not defined, this builds NO_ASSERT_PROBE0_NO_ASSERT_CUSTOM, which is just a normal identifier, which will be ignored, which results in 0 due to the SECOND in NO_ASSERT_TEST. But if NO_ASSERT_CUSTOM is defined per #define NO_ASSERT_CUSTOM, this produces NO_ASSERT_PROBE0_, which expands to ,1, which shifts 1 into the SECOND call in NO_ASSERT_TEST. Likewise if NO_ASSERT_CUSTOM is defined per -DNO_ASSERT_CUSTOM on the command line, that would (typically) make its definition equivalent to #define NO_ASSERT_CUSTOM 1, which would produce NO_ASSERT_PROBE0_1, which expands to ,1.
The cases for when NO_ASSERT_KEY is not defined are similar.
There's probably a prettier way to build this construct, if anyone wants to take a shot.
The following code:
#define MYDEF(x)
#define MYDEF(y)
int main() {}
gives me an error (or warning if pedantic-errors is disabled):
'MYDEF' macro redefined
The reason is different names for unused argument (more over, there is no body in macro). But why? In which situations it can be a problem?
Because macros are not functions. They are textual replacements done by the preprocessor and can't be overloaded.
It is (almost) similar to find and replace in your editor. Find all the occurences of MYDEF and replace it with (empty string in your case). It's more complicated, of course, but the idea is the same.
And you can't overload this find and replace, can you? :)
The macro can be redefined, and the macro is uniquely determined by the macro name. For example, code like this :
#define MYDEF(x) //the name of the macro is 'MYDEF'
#define MYDEF(x, y) //the name of the macro is 'MYDEF' too
MYDEF(x) will be redifined(or covered) by MYDEF(x, y), you can't write code MYDEF(x) any more after defining MYDEF(x, y)
so, if you write code :
#define MYDEF(x)
#define MYDEF(y) //(There compiler will give warning). You can write
//`#undef MYDEF` before `#define MYDEF(y)` to avoid it.
MYDEF(x) will be redifined by MYDEF(y).
I am trying to compare to a defined constants in C, and I have simplified my program to the following:
#include "stdio.h"
#include "stdlib.h"
#define INVALID_VALUE -999;
int main(void)
{
int test=0;
if(test==INVALID_VALUE) //The error line..
return INVALID_VALUE;
return 0;
}
And when I use gcc to compile, it gives out error "error: expected ‘)’ before ‘;’ token".
Is there any reason that this cannot be done?
Remove the semicolon from your INVALID_VALUE definition.
Macros are replaced lexically (character-by-character) with no understanding of the syntax around them. Your macro INVALID_VALUE is set to -999;, so your if line expands the macro to:
if (test==-999;)
which is invalid C syntax.
You need to remove the ; in #define INVALID_VALUE -999;. See the fixed code.
You could have worked towards this conclusion by understanding what the error message expected ‘)’ before ‘;’ token was telling you. It's telling you that it expected to find a ) before the ; token, but from inspecting the line alone you don't see a ;. So maybe there's one in the definition of INVALID_VALUE? Look up at #define INVALID_VALUE -999; and there it is! Think it should be there, but not sure? So let's try remove it and see if it works. Success!
This page goes and explains why you shouldn't conclude a #define with a semicolon, even if it is needed in the use of the macro. It's good to learn as much as possible from your mistake so that you don't make it again. Quote:
Macro definitions, regardless of
whether they expand to a single or
multiple statements should not
conclude with a semicolon. If
required, the semicolon should be
included following the macro
expansion. Inadvertently inserting a
semicolon at the end of the macro
definition can unexpectedly change the
control flow of the program.
Another way to avoid this problem is
to prefer inline or static functions
over function-like macros.
In general, the programmer should
ensure that there is no semicolon at
the end of a macro definition. The
responsibility for having a semicolon
where needed during the use of such a
macro should be delegated to the
person invoking the macro.
The C Preprocessor Macro Language is Distinct from C
The ; in the macro definition should be removed.
This is an understandable mistake. If C were designed today, the macro language might be more integrated with the rest of C.
But on 16-bit machines in the early 1970's when C was invented, it was unwise to write an overly complicated program. It would end up useless as there would be no memory remaining to actually run the big masterpiece program, and even simple programs ran slowly.
So C was split into a rather simple macro preprocessor that was, originally, a completely separate program, and the compiler proper. The preprocessor program made no attempt to parse C beyond understanding the lexical analysis model.
When 32-bit machines took over, the preprocessor was typically integrated into the parser, but naturally the language needed to remain the same.
The semi colon at the end of
#define INVALID_VALUE -999;
Classic.
You do not need a semicolon after defining something. #define is actually a macro, and it will do an inline expansion on compile.
Thus,
#define IDENTIFIER 10;
int j = IDENTIFIER;
will expand as:
int j = 10;;
Change macro
from:
#define INVALID_VALUE -999;
to
#define INVALID_VALUE -999
Bye
I know that this code is valid both in C and C++:
#define FOO 0
#define FOO 0
ISO/IEC 14882:2011
16.3 Macro replacement [cpp.replace]
2 An identifier currently defined as an object-like macro may be
redefined by another #define preprocessing directive provided that the
second definition is an object-like macro definition and the two
replacement lists are identical, otherwise the program is ill-formed.
Likewise, an identifier currently defined as a function-like macro may
be redefined by another #define preprocessing directive provided that
the second definition is a function-like macro definition that has the
same number and spelling of parameters, and the two replacement lists
are identical, otherwise the program is ill-formed.
But what about this code?
#define FOO 0
#define FOO FOO
Replacement lists are not identical at the start of preprocessing (only when the first replacement occurs).
This is not allowed in either C or C++. The replacement list must be identical. What you're talking about (after the first pass) is the result of processing the replacement list1, not the replacement list itself. Since the replacement list itself is not identical, the code is not allowed.
1 Or at least what the result would be if the preprocessor worked a particular way that happens to be different from how it actually does.
I want to simplify things, by not creating a list of enum separately, but create the enums along the function call which creates the data where i point with those enums.
I tried to make #define which would create another #define, but it didnt work:
int defcounter = 0;
#define make_def(enumname, somedata) \
#define enumname defcounter \
defcounter++; \
func_call(somedata); \
void createstuff(){
make_def(MY_ENUM_NAME, mydata);
make_def(MY_OTHER_ENUMNAME, mydata);
}
void dostuff(){
somefunc_call(MY_ENUM_NAME);
somefunc_call(MY_OTHER_ENUMNAME);
}
But this will create error at the #define enumname:
error C2162: expected macro formal parameter
How can I make this work?
It is impossible to create new types (classes, enums, unions, whatever) at runtime in C++. One of the major features of C++ is that it is statically typed - all types must be known at compile time.
Preprocessor commands (#define, #if, #pragma, #include, ...) cannot appear in macros / defines. The problem is, that the CPP (C-Preprocessor) seperates commands by newlines, while C and C++ are unaware of newlines. In C/C++ you can write everything on one line, for preprocessor commands, you can't.
#define MY_MACRO(name) \
#define name##_macro something_cool \
enum name{ \
.... \
}
// somewhere else
void myfunc(){
MY_MACRO(myfunc_enum);
}
Now, at preprocessing time, those lines all get glued into one big line, thanks to the \ backslash:
#define MY_MACRO(name) #define name##_macro something_cool enum name{....}
Now, how would that macro look at usage?
void myfunc(){
#define name##_macro something_cool enum name{....};
}
Now, the preprocessor has to run over that #define again. But exactly what belongs to the #define, and what doesn't? For the coder it was clear when the macro was written in seperate lines, but now it isn't anymore.
What exactly is your desired output? You need to explain what you think you might get as output from the C preprocessor.
You have scope problems and an attempt to define a macro inside the replacement text of another macro.
Scope
The macro make_def() invokes an undefined function 'func_call'. The createstuff() function uses an undefined variable mydata. And function dostuff() seems to call an undefined function somefunc_call() with an enum that might, perhaps, have been defined inside a separate function.
If an enumeration is defined inside one function, that enumeration is not available to code outside that function, and specifically is not available to either called functions or calling functions. That alone limits the utility of what you seem to be attempting to do. (Yes, the enumeration values might be implicitly converted to int or some similar type, but it is not really the enumeration type that is being used.)
Defining macros in macros
You cannot create a macro that itself contains #define or any other preprocessor directive in its replacement text.
If the outer macro is invoked, the expansion does not interpret the inner #define as being a preprocessor directive, so it almost always ends up as an error, In context the # must be a stringize operator, and the word 'define' after it would have to be the name of an argument to the outer macro to have a chance of working.
// Does not work as intended
#define macro(define, prefix) #define another(name) foo(prefix ## name)
macro(something, other);
Generates:
"something" another(name) foo(othername);
The _Pragma in C99 is a partial exception to the 'a macro expansion cannot contain a preprocessor directive', but it (_Pragma) does not start with #.
Your macro is incorrect, since you cannot use a macro to create another macro, unfortunately, as the toke # has special meaning in the expansion-list: it can either quote a macro argument, or expand another macro. One easy (albeit poorly designed) way you could do this is just to use old c-style #define MY_ENUM_NAME valueas c macro do not respect scope, but this would not be good design. Another possibility is to pass in string arguments and hash on them, but all depends on what you want to do.