macro definition - c

I tried to define a macro functioned as below. Call 1 has no problem, but Call 2 prompted compiler error because 3rd argument is not available. How to define a macro which support both call 1 and call 2?
#define RDF_LOG(dbglevel, fmt, ...) (rdfDBG(dbglevel, " " fmt, __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }
RDF_LOG(kERROR, "Fail to open file %s\n", pinfile); /* Call 1 */
RDF_LOG(kERROR, "Insufficient Memory\n"); /* call 2 , compiler -> error: expected expression before ')' token */

You're getting an extra comma in the second macro expansion, because you have an unconditional comma after fmt in the macro definition.
Dropping the fmt parameter from the macro definition seems to fix the problem; the format string then becomes part of __VA_ARGS__:
#define RDF_LOG(dbglevel, ...) (rdfDBG(dbglevel, " " __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }
RDF_LOG(kERROR, "Fail to open file %s\n", pinfile); /* Call 1 */
RDF_LOG(kERROR, "Insufficient Memory\n");
This expands to:
void rdfDBG(int dbglevel, const char *fmt, ...) { }
(rdfDBG(kERROR, " " "Fail to open file %s\n", pinfile));
(rdfDBG(kERROR, " " "Insufficient Memory\n"));
Incidentally, it looks like the " " is intended to require the format to be a string literal (and my modified version preserves this). Are you sure you want to do that? Though it's rare, it can be useful to have a non-literal format string.

GCC Extensions
GCC has an extension to handle that (note the missing comma before the ...):
Incorrect (references __VA_ARGS__ which is not allowed in the GCC extension):
#define RDF_LOG(dbglevel, fmt ...) (rdfDBG(dbglevel, " " fmt, __VA_ARGS__))
Correct (not referencing __VA_ARGS__):
#define RDF_LOG(dbglevel, fmt...) (rdfDBG(dbglevel, " " fmt))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }
enum { kERROR };
void x(const char *pinfile);
void x(const char *pinfile)
{
RDF_LOG(kERROR, "Fail to open file %s\n", pinfile);
RDF_LOG(kERROR, "Insufficient Memory\n");
}
You can tell I don't use the GCC extension - because I use some compilers that are not GCC.
There is also the second (GCC-specific) mechanism mentioned by Adam in his comment:
#define RDF_LOG(dbglevel, fmt, ...) (rdfDBG(dbglevel, " " fmt, ## __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }
enum { kERROR };
void x(const char *pinfile);
void x(const char *pinfile)
{
RDF_LOG(kERROR, "Fail to open file %s\n", pinfile);
RDF_LOG(kERROR, "Insufficient Memory\n");
}
Standard C99
Failing that, you have to use the C99 standard mechanism:
#define RDF_LOG(dbglevel, ...) (rdfDBG(dbglevel, " " __VA_ARGS__))
void rdfDBG(int dbglevel, const char *fmt, ...) { /* printf debug message */ }
RDF_LOG(kERROR, "Fail to open file %s\n", pinfile); /* Call 1 */
RDF_LOG(kERROR, "Insufficient Memory\n");
This basically cheats or circumvents the problem for this context. In the general case, C99 requires a comma and at least one argument.

Related

How to use parameters const char *format in custom printf

I'm looking for a function that print log information, in order to debug my program.
This function must look at a boolean and decide if write the log in a file or to the console.
int useFile;
int log_informations( ? )
{
if(useFile)
{
// open/close FILE *pf omitted
fprintf(pf, ? );
}
else
{
printf( ? );
}
return 0;
}
int main()
{
int answer = 42;
log_informations("The answer is %d.", answer);
return 0;
}
Can you help me with the parameter? I did not found any reference.
NB: In this question I made things clear and simpler as they were in my context, so I do not need workaround but, possibly, a simple answer.
Thank you in advance ;)
As other mentioned, you don't need to actually write a function. A macro could help here:
#define LOG(fmt, ...) fprintf(logToFile ? fileLogger : stdout, fmt, ##__VA_ARGS__)
To answer your question you can look at how printf and vprintf work:
int printf(const char *format, ...);
int vprintf(const char *format, va_list arg);
printf is a variadic function and you want to provide your own version that wraps vprintf and vfprintf.
#include <stdarg.h> // needed for va_list, va_start, and va_end.
int my_printf(const char *format, ...)
{
va_list ap;
int ret;
va_start(ap, format);
if (useFile) ret = vfprintf(pf, format, ap);
else ret = vprintf(format, ap);
va_end(ap);
return ret;
}
EDIT: as #phuclv mentioned, if you want to include file, line, and/or function information in your log a macro is the only way. For example, for appending file and line information you could do something like this:
#define LOG(fmt, ...) fprintf(logToFile ? fileLogger : stdout, __FILE__ ":" STRINGIFY(__LINE__) " " fmt, ##__VA_ARGS__)
#define STRINGIFY_HELPER(x) #x
#define STRINGIFY(x) STRINGIFY_HELPER(x)
You need STRINGIGY for __LINE__ because it is an int.

Variadic Macro calling fprintf: how to add arguments to __VA_ARGS__?

I have two macros:
#define LogFunction(str) fprintf(stdout, "%s: %s\n",__FUNCTION__,(str))
#define LogPrintf(f_, ...) fprintf(stdout, (f_), ##__VA_ARGS__)
So i can use them this way:
void MyFunction()
{
int N=4;
LogFunction("START"); // Outputs "MyFunction: START"
LogPrintf("N=%d\n", N); // Outputs "N=4"
}
What I would like to change is to
add FUNCTION at the start of the LogPrintf as it is in LogFunction
add "\n" at the end of the LogPrintf without having to remember to put it in myself
so in the end i could have just one macro for my outputs.
I've tried to understand if Appending to __VA_ARGS__ could've been useful, but i admit that i've not understood if it is related to my case :(
Thanks.
why not doing it in 3 steps?
#define LogPrintf(f_, ...) do { fprintf(stdout, "%s: ",__FUNCTION__); \
fprintf(stdout, (f_), ##__VA_ARGS__); \
fprintf(stdout,"\n"); } while(0)
this does 3 prints, but at least it's simple and does what you want. the do while(0) trick makes sure this is one only block (when using if without braces) and requires semicolon.
If you're willing to rely on the first argument to LogPrintf being a string literal, then you should be able to use string concatenation to achieve your objective:
// Assumes f_ always corresponds to a string literal:
#define LogPrintf(f_, ...) fprintf(stdout, "%s: " f_ "\n", __FUNCTION__, ##__VA_ARGS__)
Note, however, that in standard C, the LogPrintf macro requires at least two arguments, and the ## has no place. I keep it here only because you use it in your original code.
If you must accept format string expressions other than string literals, however, then your simplest alternative is to perform multiple I/O calls, as another answer also suggests:
#define LogPrintf(f_, ...) do { \
fprintf(stdout, "%s: ", __FUNCTION__); \
fprintf(stdout, (f_), ##__VA_ARGS__); \
fputc('\n', stdout); \
} while (0)
Note that in this case, the macro expands to a statement (sans trailing semicolon), whereas in the other, the macro expands to an expression. If you want the return value(s) of any of the I/O functions, then you'll have to make special provisions for that in this case.
If that doesn't work for you either, then the ultimate alternative is to write and use a helper function, as was suggested in comments:
#define LogPrintf(f_, ...) log_printf_impl(stdout, __FUNCTION__, (f_), ##__VA_ARGS__)
int log_printf_impl(FILE *f, const char *func, const char *fmt, ...) {
static const char prefix[] = "%s: ";
size_t flen = strlen(fmt);
va_list args;
int result = -1;
char *aug_fmt = malloc(sizeof(prefix) + strlen(fmt) + 1);
if (aug_fmt) {
va_start(args, fmt);
sprintf(aug_fmt, "%s%s\n", prefix, fmt);
result = vfprintf(f, aug_fmt, func, args);
va_end(args);
free(aug_fmt);
}
return result;
}

How to add file name to syslog string?

I'm writing an embedded application in C in Linux user-space.
I need to add the file name and function name to syslog string.
how can i do that ?
note: to better explain my self, i need to define a macro that fills in the file name and func name..
what i did was the follwing:
#define LOG(prio, ...) my_log(__FILE__, __LINE__, __func__, prio, __VA_ARGS__)
and the problem is in the implementation of my_log:
void my_log(const char *file, int line, const char *func, int prio, const char *fmt, ...)
{
//how to add the "filename:line, funcname: " string to the fmt string
va_start(args, full_fmt);
vsyslog(prio, full_fmt, args);
va_end(args);
}
syslog accepts a printf like format string. You are probably referring to something along the lines of:
syslog(1, "%s:%d: something bad happened", __FILE__, __LINE__);
__FILE__ automatically expands to a string containing the current source file. __LINE__ similarly expands to the current line in the current file.

fprintf macro with single param expecting ')'

I got next debug macro, which works fine:
#ifndef NDEBUG
#define errorLog(fmt, ...) fprintf(stderr, "[ERROR %s: %d] " fmt "\n", __FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif
Except if i try next line (which produce expected a ')' error):
const char* someMessage = "Message";
errorLog(someMessage);
But this one produce no errors:
errorLog("Message");
Right now i solve this like:
const char* someMessage = "Message";
errorLog("%s", someMessage);
How to change macro to work with single const char* param as well?
const char* someMessage = "Message";
errorLog(someMessage); //fprintf(stderr, someMessage)
As written, your errorLog requires a string literal for the first (fmt) argument, as it tries to use string concatenation, which only works with string literals. If you want a macro that can take any char *, not just a string literal, you have to use it directly, rather than pasting. You could use something like:
#define errorLog(...) \
(fprintf(stderr, "[ERROR %s: %d] ", __FUNCTION__, __LINE__), \
fprintf(stderr, __VA_ARGS__), \
fprintf(stderr, "\n"))
This will work for any char *, but will not have the same return value, if you care about that. This also has the advantage that it doesn't depend on the gcc , ## __VA_ARGS__ extension which may not work on other compilers.
If you want this to work properly in a multithreaded program, you might need:
#define errorLog(...) \
(flockfile(stderr), \
fprintf(stderr, "[ERROR %s: %d] ", __FUNCTION__, __LINE__), \
fprintf(stderr, __VA_ARGS__), \
fprintf(stderr, "\n"), \
funlockfile(stderr))
instead

Issue with logging in C

I have many functions and while entering each function, I am calling a Macro FUNC_ENTRY, which is in turn calling the default logging macro (LOGGING).
To be specific, this is my FUNC_ENTRY macro:
#define FUNC_ENTRY LOGGING(ONE, "Entry");
My LOGGING macro is defined as below:
#define LOGGING(prio, my_var, ...) \
{\
char priority[6];\
bzero(level,4); \
if (prio == ONE) { sprintf(priority,"ONE");} \
if (prio == TWO) { sprintf(priority,"TWO");} \
if (prio == THREE) { sprintf(priority,"THREE");} \
fprintf(fp,"%s: %s: %s: %d: %s:%s|\n",__DATE__, __TIME__, __FILE__,__LINE__, __func__,level);\
fflush(fp); \
fprintf(fp,my_var,##__VA_ARGS__);\
fflush(fp); \
fprintf(fp,"\n");\
fflush(fp); \
}
OK, now my question is, whenever I enter any function, my LOGGING macro should print "Entry to xyz function". As of now, it only prints "Entry". Any clue how to achieve this?
The way I am calling the FUNC_ENTRY macro is as below.
Suppose I have a function xyz;
void xyz {
FUNC_ENTRY;
/*other statements*/
}
There are a number of issues:
That's two too many fflush(fp) calls for most purposes, unless you think you often write buggy code.
'Tis odd that you zero level, declare and set priority, but print level which is still all zeros.
That fragment is big enough to warrant a function.
You don't want the semi-colon after #define FUNCENTRY.
'Tis also odd that you think you should get Entry to xyz function when you don't include to or function in the strings in the macro.
It also seems pointless reporting the time and date when the file was compiled in your error messages (which is what __DATE__ and __TIME__ are for).
Fixing some of those issues leads to:
#define FUNC_ENTRY LOGGING(ONE, "Entry to %s function\n", __func__)
#define LOGGING(prio, my_var, ...) \
{\
char priority[6];\
memset(priority, '\0', sizeof(priority)); \
if (prio == ONE) { sprintf(priority, "ERR");} \
if (prio == TWO) { sprintf(priority, "TWO");} \
if (prio == THREE) { sprintf(priority, "THREE");} \
fprintf(fp,"%s: %s: %s: %d: %s:%s|\n", __DATE__, __TIME__, __FILE__, __LINE__, __func__, priority);\
fprintf(fp, my_var, ##__VA_ARGS__); \
fprintf(fp,"\n"); \
fflush(fp); \
}
I note that , ##__VA_ARGS__ is a GCC extension over standard C. The bzero() function was marked obsolescent in POSIX 2004 and is missing from POSIX 2008; it is best not to use it.
It is not clear, but judging from the code, you have a global (or, at least, file scope) variable FILE *fp; which is initialized to the log file you want to write to. Ick; and likewise yuck!
Were it my code (and I wanted the Entry to xyz function message spelled thus), I'd probably use:
extern void err_logger(int level, int line, char const *file, char const *func, ...);
and
#define FUNC_ENTRY LOGGING(ONE, "Entry to %s function\n", __func__)
#define LOGGING(prio, ...) \
err_logger(level, __LINE__, __FILE__, __func__, __VA_ARGS)
And the implementation of err_logger() might be:
void err_logger(int level, int line, char const *file, char const *func, ...)
{
char *priority = "";
if (level == ONE) priority = "ERR";
if (level == TWO) priority = "TWO";
if (level == THREE) priority = "THREE";
time_t t = time(0);
char date_time[32];
strftime(date_time, sizeof(date_time), "%Y-%m-%d %H:%M:%S", gmtime(&t));
fprintf(logfp, "%s: %s: %d: %s: %s|\n", date_time, file, line, func, priority);
va_list args;
va_start(args, func);
char *fmt = va_arg(args, char *);
vfprintf(logfp, fmt, args);
va_end(args);
fflush(logfp);
}
Where logfp would be the log file stream and would be private to the file that holds the source for err_logger().
I've not compiled that code; there could be minor errors in it. It does, however, give you the general idea of what to do and how to do it — I think.
Something along these lines:
#include <stdio.h>
#define T printf("Entering %s\n", __func__)
int main(void)
{
T;
return 0;
}
Unfortunately it looks like you're not going to be able to concatenate that to your string at compile time (see here: Can I substitute __func__ into an identifier name in a C macro?). There may be some other compiler specific or C++ specific tricks but otherwise you will need to build your string at run time.

Resources