473,805 Members | 2,010 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

variadic macros and and empty replacement for __VA_ARGS__

I want to write a macro that produces debug output and has a variable
number of arguments, so that I can use like this:

int i;
char *s;

DBG("simple message\n");
DBG("message with an int argument, value is %d\n", i);
DBG("two arguments: int %d, strings %s\n", i, s);

The output should be a fixed prefix, say "DEBUG ", followed by the
function name the macros is used in, and then by the string passed to
the macro, including further arguments.

The best solution I have found so far, is

#define DBG(fmt, ...) printf("DEBUG %s:" fmt, __func__, __VA_ARGS__)

This works as intended as long as there is at least one argument
following the format strings, but it expands to
printf("DEBUG %s:" fmt, __func__,) when there is no argument and that
causes a syntax error.

The draft of C99 I have here, disallows to give no arguments for the
ellipsis ... as stated in 6.10.3:

[#4] If the identifier-list in the macro definition does not end
with an ellipsis, the number of arguments, including those
arguments consisting of no preprocessing tokens, in an invocation
of a function-like macro shall agree with the number of parameters
in the macro definition. Otherwise, there shall be more arguments
in the invocation than there are parameters in the macro
definition (excluding the ...). There shall exist a )
preprocessing token that terminates the invocation.
Is there a better way to write the DBG() macro to avoid this?

urs
Mar 27 '06
15 14284
Michael Mair wrote:
raxip schrieb:
This works as intended as long as there is at least one argument
following the format strings, but it expands to
printf("DEB UG %s:" fmt, __func__,) when there is no argument and that
causes a syntax error.


#define macroFunc(a,b,. ..) ( Func(a, b, ##__VA_ARGS__) )


This is "gcc-C".
It is not valid C99, though.


I believe it can be valid C99 if the result of macroFunc(...) is
stringized, and __VA_ARGS__ is empty. (Of course, in that case, it's
useless and doesn't answer the question.)

As for the original question, I had taken a look at a non-GCC way of
writing ,##__VA_ARGS__ earlier. I don't recommend anyone actually use
this for hopefully obvious reasons, but in case anyone cares, here it
is. Please let me know if there are bugs in it (there may well be).

#include <stdio.h>

#define CONCAT(x, y) CONCAT_(x, y)
#define CONCAT_(x, y) x##y

#define ID(...) __VA_ARGS__

#define IFMULTIARG(if,t hen,else) \
CONCAT(IFMULTIA RG_, IFMULTIARG_(if, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 0, ))(then,else)
#define IFMULTIARG_(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, \
_10, _11, _12, _13, _14, _15, _16, _17, _18, _19, \
_20, _21, _22, _23, _24, _25, _26, _27, _28, _29, \
_30, _31, _32, _33, _34, _35, _36, _37, _38, _39, \
_40, _41, _42, _43, _44, _45, _46, _47, _48, _49, \
_50, _51, _52, _53, _54, _55, _56, _57, _58, _59, \
_60, _61, _62, _63, ...) _63
#define IFMULTIARG_0(th en, else) else
#define IFMULTIARG_1(th en, else) then

#define PROVIDE_SECOND_ ARGUMENT(x, ...) \
CONCAT(IFMULTIA RG(ID(__VA_ARGS __), INSERT_, ADD_), \
SECOND_ARGUMENT ) (x, __VA_ARGS__)
#define ADD_SECOND_ARGU MENT(x, y) y, x
#define INSERT_SECOND_A RGUMENT(x, y, ...) y, x, __VA_ARGS__

#define DEBUG(...) printf("DEBUG %s: " \
PROVIDE_SECOND_ ARGUMENT(__func __, __VA_ARGS__))

int main() {
DEBUG("1\n");
DEBUG("%d\n", 2);
DEBUG("%d %d\n", 1, 2);
}

Mar 27 '06 #11
Groovy hepcat Urs Thuermann was jivin' on 27 Mar 2006 15:34:46 +0200
in comp.lang.c.
variadic macros and and empty replacement for __VA_ARGS__'s a cool
scene! Dig it!
I want to write a macro that produces debug output and has a variable
number of arguments, so that I can use like this:

int i;
char *s;

DBG("simple message\n");
DBG("message with an int argument, value is %d\n", i);
DBG("two arguments: int %d, strings %s\n", i, s);

The output should be a fixed prefix, say "DEBUG ", followed by the
function name the macros is used in, and then by the string passed to
the macro, including further arguments.


I think this should work:

#define DBG(...) printf("DEBUG $s: ", __func__), printf(__VA_ARG S__)

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technicall y correct" English; but since when was rock & roll "technicall y correct"?
Mar 29 '06 #12
> I think this should work:

#define DBG(...) printf("DEBUG $s: ", __func__), printf(__VA_ARG S__)


This is the first answer in this thread, which seems to understand my
post and solves the problem of inserting the __func__ between the fmt
and __VA_ARGS__ without having the ,) when __VA_ARGS__ is empty.

I wanted to avoid calling printf() twice, because I need this in the
linux kernel (with printk instead of printf) and I'd prefer it to be
atomic. Also, I can't make a function debug(char *name, char *fmt, ...)
and call printk() from there, because the linux kernel doesn't have
vprintk().

But I will follow your suggesstion and will do it like follows:

#ifdef DEBUG
int debug = 0;
#define DBG(...) (debug & 1 ? (printk(KERN_DE BUG "%s: ", __func__), \
printk(__VA_ARG S__)) : 0)
#else
#define DBG(...)
#endif

where KERN_DEBUG is a string constant defined in the linux kernel
sources.

urs
Mar 31 '06 #13
Couldn't you get rid of the int debug = 0 using this?:

#define DEBUG 1

#ifdef DEBUG
#define DBG(...) (DEBUG ? (printk(KERN_DE BUG "%s: ", __func__), \
printk(__VA_ARG S__)) : 0)
#else
#define DBG(...)
#endif

Mar 31 '06 #14
pemo wrote:

Urs Thuermann wrote:
I think this should work:

#define DBG(...) printf("DEBUG $s: ", __func__), printf(__VA_ARG S__)


This is the first answer in this thread, which seems to understand my
post and solves the problem of inserting the __func__ between the fmt
and __VA_ARGS__ without having the ,) when __VA_ARGS__ is empty.

I wanted to avoid calling printf() twice, because I need this in the
linux kernel (with printk instead of printf) and I'd prefer it to be
atomic. Also, I can't make a function debug(char *name, char *fmt, ...)
and call printk() from there, because the linux kernel doesn't have
vprintk().

But I will follow your suggesstion and will do it like follows:

#ifdef DEBUG
int debug = 0;
#define DBG(...) (debug & 1 ? (printk(KERN_DE BUG "%s: ", __func__), \
printk(__VA_ARG S__)) : 0)
#else
#define DBG(...)
#endif

where KERN_DEBUG is a string constant defined in the linux kernel
sources.

Couldn't you get rid of the int debug = 0 using this?:

#define DEBUG 1

#ifdef DEBUG
#define DBG(...) (DEBUG ? (printk(KERN_DE BUG "%s: ", __func__), \
printk(__VA_ARG S__)) : 0)
#else
#define DBG(...)
#endif

Apr 1 '06 #15
"pemo" <us***********@ gmail.com> writes:
Couldn't you get rid of the int debug = 0 using this?:

#define DEBUG 1

#ifdef DEBUG
#define DBG(...) (DEBUG ? (printk(KERN_DE BUG "%s: ", __func__), \
printk(__VA_ARG S__)) : 0)
#else
#define DBG(...)
#endif


No, your code doesn't make sense.

In my code, debug is initialized to zero (i.e. no debug output) but
can be set at module load time. There are other debug macros, that
test for debug&2 and debug&4.

urs
Apr 3 '06 #16

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
6632
by: jois.de.vivre | last post by:
Hi, I'm writing a C++ program that uses C style macros for debugging purposes. I have code that looks something like this: #define DEBUG(str, ...) Show(__FILE__, __LINE__, str, ## __VA_ARGS__); void Show(const char* file, int line, const char* display, ...) {
4
13574
by: Augustus S.F.X Van Dusen | last post by:
I have recently come across the following construction: #define P_VAR(output, string, args...) \ fprintf (output, "This is "string"\n", ##args) which can be invoked as follows: int x = 1, y = 2 ; char * str = "String" ;
3
2045
by: Trent Buck | last post by:
(Note: C99 supports variadic macros, but C89 does not.) I'm pretty sure what I'm trying to do is impossible, but I'll ask here in case I'm missing something. I'm trying to define generic, variadic arithmetic and boolean operators. For example, product (2, sum (3, 4), 5);
7
1626
by: Michael B Allen | last post by:
If I define a variadic macro like say: #define PRINT(fmt, ...) _myprintf(__FILE__ ": " fmt, __VA_ARGS__) and I call this like: PRINT("no args"); the preprocessor generates:
3
2587
by: Thomas Carter | last post by:
I understand that C99 supports variadic macros. However, is it not the case that a variadic macro defined as #define SAMPLE_MACRO(...) Bloody-blah must take at least one argument? I would be interested to allow for no arguments at all. Is this possible?
12
6546
by: Laurent Deniau | last post by:
I was playing a bit with the preprocessor of gcc (4.1.1). The following macros expand to: #define A(...) __VA_ARGS__ #define B(x,...) __VA_ARGS__ A() -nothing, *no warning* A(x) -x B() -nothing, *warning ISO C99 requires rest arguments to be used*
8
3454
by: Christof Warlich | last post by:
Hi, is there any way to access individual elements in the body of a variadic macro? I only found __VA_ARGS__, which always expands to the complete list. Thanks for any help, Christof
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10613
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10368
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10107
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.