What is the use/applicability of macro function without definition:
#ifndef __SYSCALL
#define __SYSCALL(a, b)
#endif
One can find this macro in Linux system in header file /usr/include/asm/msr.h
I also notice macro of following kind.
#define _M(x) x
And only reason to defined this kind of macro that I can think to make code uniform. like in #define SOMETHING (1 << 0). Is there any other hidden(better) use of this kind of macros?
An answer with example will be very helpful. Also
can someone provide me a text/link to read about this.
One of the most common case of a macro of this form:
#define _M(x) x
is to provide backwards compatibility for compilers that only supported the original K&R dialect of C, that predated the now-ubiquitous ANSI C dialect. In the original K&R dialect of the language, function arguments were not specified when declaring the function. In 1989, ANSI standardized the language and incorporated a number of improvements, including function prototypes that declared the number of type of arguments.
int f(int x, double y); /* ANSI C. K&R compilers would not accept this */
int f(); /* Function declared in the original K&R dialect */
While compilers that support the original K&R dialect of C are rare (or extinct) these days, a lot of software was written when both kinds of compilers needed to be supported, and macros provided an easy way to support both. There are still a lot of headers laying about that provide this backwards compatibility.
To provide backwards compatibility for K&R compilers, many header files have the following:
#if ANSI_PROTOTYPES
# define _P(x) x
#else
# define _P(x) ()
#endif
...
int f _P((int x, double y));
If the ANSI_PROTOTYPES definition has been correctly set (either by the user or by some prior #ifdef logic), then you get the desired behavior:
If ANSI_PROTOTYPES is defined, the definition expands to int f(int x, double y).
If ANSI_PROTOTYPES is not defined, the definition expands to int f()
This is often used with conditional expressions to disable a macro by causing it to be preprocessed to nothing. For example (simplified):
#ifdef DEBUG
#define ASSERT(x) if(!(x)) { abort(); }
#else
#define ASSERT(x) /* nothing */
#endif
Just a follow-up to my question.
I got good answers. but I am also adding some more helpful example where macros without definition are useful, one can find it helpful in future:
(1): Why do I see THROW in a C library?
uses to share header file between C and C++. The macro name is _THROW(x)
#ifdef __cplusplus
#define __THROW(x) throw(x)
#else
#define __THROW(x)
#endif
(2) to eliminate warnings when a function parameter isn't used:
This use is for c++. In C it will cause an error too few arguments But in C++ it works with no error: (codepad linked)
#define UNUSED(x)
int value = 0;
int foo(int UNUSED(value))
{
return 42;
}
int main(){
foo(value);
}
(for this I added c++ tag in my question)
Additionally,
(3): The use of #define _M(x) x is as follows, just to makes code line up uniformly:
/* Signed. */
# define INT8_C(c) c
# define INT16_C(c) c
# define INT32_C(c) c
# if __WORDSIZE == 64
# define INT64_C(c) c ## L
# else
# define INT64_C(c) c ## LL
# endif
the file is: /usr/include/stdint.h
It means that code that uses that macro will conditionally preprocess away to nothing.
As simple examples, consider debug code, logging or assertions.
This is probably a debug macro or an platform macro. For example lets say I have a debugger attached to INT3. I might have this when I'm debugging
#define debug() INT3()
Then to be safe I'll add this to production code (to make sure I took them all out)
#define debug()
This looks like something similar
It could be that in some cases on some systems this code needs to make a call -- for example on a certain CPU architecture or OS. But on your system it is just no-oped.
Related
This is kind of a weird and un-Swift-thonic question, so bear with me.
I want to do in Swift something like the same thing I'm currently doing in Objective-C/C++, so I'll start by describing that.
I have some existing C++ code that defines a macro that, when used in an expression anywhere in the code, will insert an entry into a table in the binary at compile time. In other words, the user writes something like this:
#include "magic.h"
void foo(bool b) {
if (b) {
printf("%d\n", MAGIC(xyzzy));
}
}
and thanks to the definition
#define MAGIC(Name) \
[]{ static int __attribute__((used, section("DATA,magical"))) Name; return Name; }()
what actually happens at compile time is that a static variable named xyzzy (modulo name-mangling) is created and allocated into the special magical section of my Mach-O binary, so that running nm -m foo.o to dump the symbols shows something a lot like this:
0000000000000098 (__TEXT,__eh_frame) non-external EH_frame0
0000000000000050 (__TEXT,__cstring) non-external L_.str
0000000000000000 (__TEXT,__text) external __Z3foob
00000000000000b0 (__TEXT,__eh_frame) external __Z3foob.eh
0000000000000040 (__TEXT,__text) non-external __ZZ3foobENK3$_0clEv
00000000000000d8 (__TEXT,__eh_frame) non-external __ZZ3foobENK3$_0clEv.eh
0000000000000054 (__DATA,magical) non-external [no dead strip] __ZZZ3foobENK3$_0clEvE5xyzzy
(undefined) external _printf
Through the magic of getsectbynamefromheader(), I can then load the symbol table for the magical section, scan through it, and find out (by demangling every symbol I find) that at some point in the user's code, he calls MAGIC(xyzzy). Eureka!
I can replicate the whole second half of that workflow just fine in Swift — starting with the getsectbynamefromheader() part. However, the first part has me stumped.
Swift has no preprocessor, so spelling the magic as elegantly as MAGIC(someidentifier) is impossible. I don't want it to be too ugly, though.
As far as I know, Swift has no way to insert symbols into a given section — no equivalent of __attribute__((section)). This is okay, though, since nothing in my plan requires a dedicated section; that part just makes the second half easier.
As far as I know, the only way to get a symbol into the symbol table in Swift is via a local struct definition. Something like this:
func foo(b: Bool) -> Void {
struct Local { static var xyzzy = 0; };
println(Local.xyzzy);
}
That works, but it's a bit of extra typing, and can't be done inline in an expression (not that that'll matter if we can't make a MAGIC macro in Swift anyway), and I'm worried that the Swift compiler might optimize it away.
So, there are three questions here, all about how to make Swift do things that Swift doesn't want to do: Macros, attributes, and creating symbols that are resistant to compiler optimization.
I'm aware of #asmname but I don't think it helps me since I can already deal with demangling on my own.
I'm aware that Swift has "generics", but they seem to be closer to Java generics than to C++ templates; I don't think they can be used as a substitute for macros in this particular case.
I'm aware that the code for the Swift compiler is now open-source; I've skimmed bits of it in vain; but I can't read through all of it looking for tricks that might not even be there.
Here is the answer to your question about preprocessor (and macros).
Swift has no preprocessor, so spelling the magic as elegantly as MAGIC(someidentifier) is impossible. I don't want it to be too ugly, though.
Swift project has a preprocessor (but, AFAIK, it is not distributed with Swift's binary).
From swift-users mailing list:
What are .swift.gyb files?
It’s a preprocessor the Swift
team wrote so that when they needed to build, say, ten nearly-identical
variants of Int, they wouldn’t have to literally copy and paste the same
code ten times. If you open one of those files, you’ll see that they’re
mainly Swift code, but with some lines of code intermixed that are written in Python.
It is not as beautiful as C macros, but, IMHO, is more powerful.
You can see the available commands with ./swift/utils/gyb --help command after cloning the Swift's git repo.
$ swift/utils/gyb --help
usage, etc (TL;DR)...
Example template:
- Hello -
%{
x = 42
def succ(a):
return a+1
}%
I can assure you that ${x} < ${succ(x)}
% if int(y) > 7:
% for i in range(3):
y is greater than seven!
% end
% else:
y is less than or equal to seven
% end
- The End. -
When run with "gyb -Dy=9", the output is
- Hello -
I can assure you that 42 < 43
y is greater than seven!
y is greater than seven!
y is greater than seven!
- The End. -
My example of GYB usage is available on GitHub.Gist.
For more complex examples look for *.swift.gyb files in #apple/swift/stdlib/public/core.
I'm writing some code that interfaces an existing library written in C. In my Rust code I'd like to be able to use values from CPP macros. If I have a C include.h that looks like this:
#define INIT_FLAG 0x00000001
I'd like to be able to use it in Rust like this:
#[link(name="mylib")]
extern {
pub static init_flag: c_int = INIT_FLAG;
}
I've looked at other FFI code and I see a lot of people
duplicating these values in Rust instead of getting them from the FFI.
This seems a little brittle, and I'd also like to be able to handle
more complicated things that are defined via CPP macros.
Running cpp over my Rust files would only work if I'm sure my
CPP macros are only used for simple things.
It is impossible, and I don't think it will be possible in the future. C macros bring too many problems with them. If you want to run cpp over your Rust sources, you can do it manually.
If you don't want to do it and if there is a lot of constants and you also don't want to copy their values from C code to Rust you can make a C wrapper which will provide global variables with these values:
#define INIT_FLAG 0x00000001
...
const int init_flag = INIT_FLAG;
You compile this file, create a static library from it and link to it as usual:
$ gcc -c init_flag.c
$ ar r libinitflag.a init_flag.o
Rust source:
use std::libc;
#[link(name="initflag", kind="static")]
extern {
pub static init_flag: libc::c_int;
}
Rust source is nearly identical to what you tried to achieve. You will need C glue object file, however.
That's merely impossible because a C macro constant doesn't represent any object or entity at runtime. That's because the cpp preprocessor performs macro expansion (and handles the rest directives) even before compilation takes place. Consider the following snippet:
#define INIT_FLAG 0x00000001
/* some code */
unsigned dummy() { return INIT_FLAG; }
/* some other code */
Running cpp on the snippet yields preprocessed code (so called compilation unit, or translation unit) which has all occurences of INIT_FLAG replaced by the literal 0x00000001:
unsigned dummy() { return 0x00000001; }
The compilation unit then gets compiled, resulting in the object file, but now there's no trace of INIT_FLAG in it. Therefore, you cannot refer to INIT_FLAG when linking against the object file: it simply doesn't contain such symbol.
By Conditional Macro Expansion, I means something like this:
XXX(_arg) => AAA(_arg), if _arg > 0
XXX(_arg) => BBB(_arg), otherwise
To be more specific, AAA and BBB are not functions but are attribute specifiers—__attribute__ ((attribute-list)), so runtime branching does not work.
Is is possible to write macros like this? If so, how?
I imagine that it is obvious that you can write:
#define XXX(arg) ((arg) > 0) ? AAA(arg) : BBB(arg))
This is the simple way to do it. If arg is a compile-time constant, you will get only one of the two possible function calls in the code. If you want to try for an alternative, investigate the Boost Preprocessor package, and in particular IF and IIF. It works with C as well as C++.
(I renamed _arg to arg to avoid collisions with names reserved to the implementation. I'm not sure it actually matters in this context, but I'd steer clear of names starting with an underscore.)
The usual trick in this case is to use token-pasting in a way that makes your macros sort of "polymorphic". For example:
#define IFtrue(a,b) a
#define IFfalse(a,b) b
#define IF(x,a,b) IF##x(a,b)
IF(true, int, double) IF(false, foo(), main()) { }
Unfortunately, this works only if your "condition" is literally the word true or the word false; it doesn't work for things like a > 0.
What is the exact problem you're trying to solve? There's probably a better approach.
Is it OK to set debugging macros to empty string when I want to disable debug checks?
Both assert and BOOST_ASSERT are set to ((void)0) when NDEBUG is defined.
Why not to do something line this?
#ifdef NDEBUG
#define MY_DEBUG_MACRO_FUNCTION(x,y,z) ""
#elif
// define macros
#endif
The idea is for the macro to do nothing on release builds. You could define it to an empty string literal, since ""; is a valid expression. I would believe the reason of being defined to ((void)0) is so that the implementation does not emmit warnings for the expression. I have no solid grounds to say this, but some minimal testing shows that ""; generates a warning while ((void)0) doesn't. Of course, warnings are not standarized so there could be a particular implementation that does emit a warning for ((void)0) as well, but it would have to define assert to something else that doesn't on NDEBUG builds or it would be quite annoying to the user.
Not it's not ok. But you can make the "body" of the macro empty:
#define MY_DEBUG_MACRO_FUNCTION(x,y,z)
Note that there is nothing being defined, so when used nothing will be put in the source.
Going by your subject line use #undef. This is useful when there is a macro version and a C version of the function. This way you can use the compiled code over the in-lined expanded macro.
When I write something, half the effort tends to go into adding clear and concise debug output, or functionality that can be enabled/disabled when that something needs debugging.
An example of debug functionality is a downloader class where I can turn on a #define which makes it "pretend" to download the file and simply hand me back the one I have already. That way I can test to see what happens when a user downloads a file, without having to wait for the network to physically grab the file every single time. This is great functionality to have, but the code gets messier with the #ifdefs.
I eventually end up with a bunch of #defines like
// #define DEBUG_FOOMODULE_FOO
// #define DEBUG_BARMODULE_THINGAMAJIG
// ...
which are uncommented for the stuff I want to look at. The code itself turns out something like
- (void)something
{
#ifdef DEBUG_FOOMODULE_FOO
DebugLog(#"something [x = %#]", x);
#endif
// ...
#ifdef DEBUG_FOOMODULE_MOO
// etc
}
This works great for writing / maintaining the code, but it does nothing for the appearance of the code.
How do people write effortless on-the-fly long-term debug "stuff" anyway?
Note: I'm not only talking about NSLogging here... I'm also talking about stuff like the pretend-download above.
I read several libraries before writing my own and saw two approaches: macro + C functions (NSLogger) or macro + Singleton (GTMLogger, Cocoa Lumberjack).
I wrote my naive implementation here using macro + singleton. I do this during runtime:
[Logger singleton].logThreshold = kDebug;
trace(#"hi %#",#"world); // won't show
debug(#"hi %#",#"world);
You could do the same for packages instead log levels. If I want it gone, I change the #defines. Here is the code involved:
#define trace(args...) [[Logger singleton] debugWithLevel:kTrace line:__LINE__ funcName:__PRETTY_FUNCTION__ message:args];
if (level>=logThreshold){
// ...
}
If you want something more sophisticated look into Lumberjack, it has a register class facility to toggle logging for some classes.
Having two functions and then select them appropriately either at run-time or when compiling seems like a clean approach to me. This makes it possible to have one download.c and one download_debug.c file with the same functions except with different implementations. Then link with the appropriate one if you are building with -DDEBUG or not.
Otherwise, using function pointers works as well for run-time selecting functions.
If you insist of having debug code interspersed throughout your functions, you are pretty much setting up yourself for a mess :) But, you can of course break out those snippets into separate functions and then do the above (or make them no-ops as in the DLog example).
For your case, you could have separate logging macros, say MooLog and FooLog, that all conditionally compile based upon separate flags.
#ifdef DEBUG_FOO
# define FooLog(fmt, ...) NSLog((#"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define FooLog(...)
#endif
#ifdef DEBUG_MOO
# define MooLog(fmt, ...) NSLog((#"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
# define MooLog(...)
#endif
Your complex logic everywhere now becomes this:
- (void)something
{
// This only gets logged if the "DEBUG_FOO" flag is set.
FooLog(#"something [x = %#]", x);
// This only gets logged if the "DEBUG_MOO" flag is set.
MooLog(#"Something else [y = %#]", y);
}