I have a question regarding header files in C. I need to initialize a variable but depending on a condition. In order to evaluate that condition I need to call a function, see code below:
I have the following function-like-macro in header.h where I need to call function():
#define func_like_macro() do{\
if((function()==290))\
{\
macro(x, 0);\
}\
else\
{\
macro(x, 1);\
}\
macro(w, 1);\
macro(z, 1);\
}while(0);
Is this correct?
I mean will this work, or shouldn't I include at all a function call inside the function-like-macro that is in a header file?
Thanks and I apologize in advance if this is a very silly question!
Why not just have a initializer function? Normally, you will not use many global variables, so that would not be much of a problem. And for local variables, you'd need that anyways.
For the original question: A macro is just a text replacement. It is performed before the C compiler executes. Think of it as advanced text-replacement in the editor, so the function call in the macro will be inserted whereever you use that macro.
In general, function-like macros should be avoided. inline functions are often a much better approach. Here is a good rationalen not only for gcc.
Note that if you intended the variable to be initialized that way at compile-time will not work anyway. As I already nit-picked in a comment to your question, the function is actually called at run-time, never at compile-time. Therefore this macro will not help. Worse: this will not even compile, as the compiler has no idea when to call that function. Note that C has no constructors/destructors like c++ and other OOPLs.
Related
I found some legacy code with something similar to the following. Say I have the following definition:
#define FOO(x) bar
x is never referenced in the definition. So, does that mean that whatever text is placed within FOO() is irrelevant?
The code I'm looking at is scattered with calls such as FOO(someValue); I'm assuming the preprocessor is replacing the entire statement with simply bar, no matter what someValue is? A little thrown off by why x is present at all.
Yes, FOO(whatever) is completely replaced with bar in your example.
Macros like this are often seen in "configure-able" code, like:
#if defined(ENABLE_DEBUG_PRINT)
#define DEBUG_PRINT(msg) printf("Here's a message: %s\n", msg)
#else
#define DEBUG_PRINT(msg) /* empty */
#endif
Nothing special happens. Any occurrence of x in the macro definition is expanded to the value of the corresponding argument when the macro is expanded. If there is no such occurrence, it's not expanded (and the actual value of the argument is irrelevant).
As for why it's there, it may be that some past or potential future version of the macro might make some use of the argument. Perhaps it's one of several macros that take a single argument, and it's defined that way for consistency. It's impossible to tell without more context. But the macro definition is perfectly valid.
What happens is exactly what you thought would happen—the value is ignored.
I recommend running the preprocessor (gcc -E or cpp (possibly add -x c++ for c++)) to actually see what actually happens on your implementation instead of just guessing.
Yes, macro FOO() expands to bar regardless of its argument. This is not different in nature from how a function can ignore some or all of its parameters.
The macro may be a place holder for a possible future implementation that does use its argument, or a replacement for an older implementation that did. It may also be that the definition of macro FOO() is different in different places, and that some of the definitions use their argument. If it isn't any of those, nor similar, then it's just obfuscatory.
So, does that mean that whatever text is placed within FOO() is irrelevant?
Unless there's a conditionally-compiled alternative version of FOO() where x is actually used. You might that to only evaluate the expression x in the debug build, for instance.
This statement just consumes the x expression without using it.
For instance, if you want to stub some methods you can use that.
I would like to have a macro that prints it's own name (among other things), but I can't find a way to expand the macros' name in the macro itself. Basically, I want the equivalent of __FUNCTION__ for a macro name.
For example:
#define F(a, b, c) do { \
printf("%s: %s,%s,%s\n", __MACRO__, #a, #b, #c); \
c = a+b; b=a; \
} while(0)
F(x,y,z);
I would like this to print "F: x,y,z" when called.
This is indeed an XY problem.
Here is really what I'm trying to do: Soft linking symbols from a library using dlopen and dlsyms.
In order to do so the typical way i know of is:
1) Include the headers from the library.
2) Declare a variable of the type of the function you are trying to import
3) Initialize said variable with a call to dlsym
4) The call the actual function through that variable instead of calling the symbol directly.
When you have many such function to soft link, it becomes very repetitive, so macro can help.
For an full fledge example of that, see here: https://github.com/WebKit/webkit/blob/master/Source/WebCore/platform/mac/SoftLinking.h
The problem in that example and others is that you still need to manually copy the parameters list for each the functions you want to soft link.
I'm trying to improve on that, and was experimenting with macro tricks, one of which would have been helped by being able to answer my initial question.
--
Beside my soft linking issues, there are other situation where this could be useful. For example for debugging purpose, one might want to print some diagnostic information before or after every call to certain functions. One could do so by overriding functions names with macros:
#define funcA(...) \
printf("Before call to %s:%d - %d\n", #funcA, __LINE__, g_count); \
funcA(__VA_ARGS__) \
printf("After call to %s:%d - %d\n", #funcA, __LINE__, g_count);
This works well enough but if I want to do this for a bunch of function, I have to copy that macro and change funcA to funcB 4 times for each new macro. I'd rather copy it and just change the name of the macros, without having to change what's inside.
I can optimize the above by defining an internal macro p, similar to what Basile suggested:
#define funcA(...) WRAP(funcA, __VA_ARGS__)
But that's still means I need to change funcA to the new function name twice every time I copy the macro for another function.
Read more about the C preprocessor. Read the documentation of GNU cpp. Notice its stringification and concatenation abilities.
Perhaps going thru some extra internal macro might help you, so you might have a public macro like
#define FOO(X,Y,Z) PRIVATE_FOO(FOO,X,Y,Z)
with another PRIVATE_FOO macro doing stringification tricks on its first argument, maybe
#define PRIVATE_FOO(Mac,X,Y,Z) do { \
printf("%s: %s,%s,%s\n", #Mac, #X, #Y, #Z); \
Z = X+Y; Y=X; \
} while(0)
Perhaps the C preprocessor is not adequate for your task. You could generate some C code with some other tool (perhaps the GPP preprocessor, or perhaps a simple awk or python script, or perhaps some real program; you'll need to change your build process, e.g. your Makefile, to handle that). You could customize your GCC compiler with MELT if you need that. Since we don't know your actual motivations, we cannot help more.
I cannot help more, unless you motivate and clarify your question.
Your soft linking issue needs simply to use some weak symbols. It is probably unrelated to C preprocessing.
Is there any way to prevent gcc from expanding a macro in this:
#define putc(a) fputc(a)
...
void _putc(char ch) {}
struct foo { void *(putc)(char ch); }
struct foo f = {_putc;}
(&f)->putc('X'); // this is an error because it gets expanded into fputc, which is very inappropriate.
I don't want to use #undef putc because it messes up other things.
Including <stdio.h> may or may not define macro functions. In either case, a real function is provided.
It's probably not the best idea to name a function pointer like a standard library function, but you can do it. To prevent macro expansion, you have basically three options:
#undef it. You said this would mess up other things, though this shouldn't be a problem -- a real function with that name still exists. For some functions, you may miss optimizations or warnings (for functions like printf, for example), however (depending on your compiler).
Don't include the header file and declare the function yourself. I mention this for sake of completeness rather than as a real suggestion. This doesn't work if you need a type definition provided only in the header you don't want to include.
Don't put an opening parenthesis after the macro name, as in
((&f)->putc)('X'); // or (f.putc)('X'); -- looking less confusing.
I've seen many times code like this:
void func(){
#define a ...
...
#undef a
}
Is the #undef necessary at all?
It is not necessary, but the scope of a #define is global after the line it was defined. It will not obey the function scope, if you are thinking it will.
It's not necessary. If the macro is meant to be used only inside the function, it's probably a good idea to #undef it. If you don't, that just means that the macro remains visible through the rest of the translation unit (source file).
Most macros are probably intended to be visible throughout a source file anyway, so usually the question doesn't arise.
When i declare a macro like you did inside the body of a function then i would #undef it at the end. Because most probably it is meant for that function body only.
In general it is always a good idea to #undef a macro when you know that the macro definition is not going to be used anytime later because the macro definition propagate to all other files which include the file having a macro.
That depends. It is only necessary if you want to ensure that a will not be potentially available at later points in your program depending on your logic. The define is now global (in the current translation unit)!
From gnu.org:
If a macro ceases to be useful, it may be undefined with the `#undef'
directive.
Additionally,
Once a macro has been undefined, that identifier may be redefined as a
macro by a subsequent `#define' directive. The new definition need not
have any resemblance to the old definition.
and
However, if an identifier which is currently a macro is redefined,
then the new definition must be effectively the same as the old one.
Two macro definitions are effectively the same if:
Both are the same type of macro (object- or function-like).
All the tokens of the replacement list are the same.
If there are any parameters, they are the same.
Whitespace appears in the same places in both. It need not be
exactly the same amount
of whitespace, though. Remember that comments count as
whitespace.
In a previous question what I thought was a good answer was voted down for the suggested use of macros
#define radian2degree(a) (a * 57.295779513082)
#define degree2radian(a) (a * 0.017453292519)
instead of inline functions. Please excuse the newbie question, but what is so evil about macros in this case?
Most of the other answers discuss why macros are evil including how your example has a common macro use flaw. Here's Stroustrup's take: http://www.research.att.com/~bs/bs_faq2.html#macro
But your question was asking what macros are still good for. There are some things where macros are better than inline functions, and that's where you're doing things that simply can't be done with inline functions, such as:
token pasting
dealing with line numbers or such (as for creating error messages in assert())
dealing with things that aren't expressions (for example how many implementations of offsetof() use using a type name to create a cast operation)
the macro to get a count of array elements (can't do it with a function, as the array name decays to a pointer too easily)
creating 'type polymorphic' function-like things in C where templates aren't available
But with a language that has inline functions, the more common uses of macros shouldn't be necessary. I'm even reluctant to use macros when I'm dealing with a C compiler that doesn't support inline functions. And I try not to use them to create type-agnostic functions if at all possible (creating several functions with a type indicator as a part of the name instead).
I've also moved to using enums for named numeric constants instead of #define.
There's a couple of strictly evil things about macros.
They're text processing, and aren't scoped. If you #define foo 1, then any subsequent use of foo as an identifier will fail. This can lead to odd compilation errors and hard-to-find runtime bugs.
They don't take arguments in the normal sense. You can write a function that will take two int values and return the maximum, because the arguments will be evaluated once and the values used thereafter. You can't write a macro to do that, because it will evaluate at least one argument twice, and fail with something like max(x++, --y).
There's also common pitfalls. It's hard to get multiple statements right in them, and they require a lot of possibly superfluous parentheses.
In your case, you need parentheses:
#define radian2degree(a) (a * 57.295779513082)
needs to be
#define radian2degree(a) ((a) * 57.295779513082)
and you're still stepping on anybody who writes a function radian2degree in some inner scope, confident that that definition will work in its own scope.
For this specific macro, if I use it as follows:
int x=1;
x = radian2degree(x);
float y=1;
y = radian2degree(y);
there would be no type checking, and x,y will contain different values.
Furthermore, the following code
float x=1, y=2;
float z = radian2degree(x+y);
will not do what you think, since it will translate to
float z = x+y*0.017453292519;
instead of
float z = (x+y)+0.017453292519;
which is the expected result.
These are just a few examples for the misbehavior ans misuse macros might have.
Edit
you can see additional discussions about this here
if possible, always use inline function. These are typesafe and can not be easily redefined.
defines can be redfined undefined, and there is no type checking.
Macros are relatively often abused and one can easily make mistakes using them as shown by your example. Take the expression radian2degree(1 + 1):
with the macro it will expand to 1 + 1 * 57.29... = 58.29...
with a function it will be what you want it to be, namely (1 + 1) * 57.29... = ...
More generally, macros are evil because they look like functions so they trick you into using them just like functions but they have subtle rules of their own. In this case, the correct way would be to write it would be (notice the paranthesis around a):
#define radian2degree(a) ((a) * 57.295779513082)
But you should stick to inline functions. See these links from the C++ FAQ Lite for more examples of evil macros and their subtleties:
inline vs. macros
macros containing if
macros with multiple lines
macros used to paste two tokens together
The compiler's preprocessor is a finnicky thing, and therefore a terrible candidate for clever tricks. As others have pointed out, it's easy to for the compiler to misunderstand your intention with the macro, and it's easy for you to misunderstand what the macro will actually do, but most importantly, you can't step into macros in the debugger!
Macros are evil because you may end up passing more than a variable or a scalar to it and this could resolve in an unwanted behavior (define a max macro to determine max between a and b but pass a++ and b++ to the macro and see what happens).
If your function is going to be inlined anyway, there is no performance difference between a function and a macro. However, there are several usability differences between a function and a macro, all of which favor using a function.
If you build the macro correctly, there is no problem. But if you use a function, the compiler will do it correctly for you every time. So using a function makes it harder to write bad code.