How to accomplish this function in C/C++ - c++

I need a macro which helps to output the given parameter's name and value. It's something like the following code.
#define AA "Hello"
#define BB "World"
#define PRINT(input_param) printf("input_param: %s\n", (input_param))
void main()
{
PRINT(AA);
PRINT(BB);
}
I'm expecting the result: AA: Hello\n BB: World\n
But obviously it's not.
Anybody can correct me? Thanks.

You need to stringize the macro name with #. This is how assert() works as well:
#define AA "Hello"
#define BB "World"
#define PRINT(input_param) printf(#input_param ": %s\n", (input_param))
void main()
{
PRINT(AA);
PRINT(BB);
}
It may be more clear if I wrote it like this:
#define PRINT(input_param) printf("%s: %s\n", #input_param, (input_param))

Related

How to initialize parameters depending on the environment that we call a program?

In a header file I have a parameter that specifies the name of a control file:
#define CTLFILE "server.ini"
This works fine. But now I want something like this:
If I am on the server
#define CTLFILE "server.ini"
else if I am on the client
#define CTLFILE "client.ini"
How can I implement this?
You can pass option when launch your program:
For example try to call the following program passing server or client:
#include <stdio.h>
#include <string.h>
#define SERVER_FILE "server.ini"
#define CLIENT_FILE "client.ini"
int main (int argc, char *argv[])
{
if (argc<2)
{
fprintf(stderr, "You mast pass type of envirnment\n!");
return 1;
}
if (strcmp(argv[1], "server") == 0)
{
printf ("File selected: %s\n", SERVER_FILE);
}
else if (strcmp(argv[1], "client") == 0)
{
printf ("File selected: %s\n", CLIENT_FILE);
}
else
{
fprintf(stderr, "Not supported environment %s", argv[0]);
return 1;
}
return 0;
}
You can use conditional compilation by using #ifdef....#endif pair.
For example, in the code, put it like
#ifdef SERVERSIDE
#define CTLFILE "server.ini"
#else
#define CTLFILE "client.ini"
#endif
Then, while compiling, pass -DSERVERSIDE option to the compiler (reference: gcc).
You can't do this that way, because #define and all #something are preprocessor instruction. That mean that after compilation, all #something are "gone", so you can't execute the same program differently with preprocessor instruction.
Many choice :
*) You compile twice the program with different #define CTLFILE.
*) You develop something like a configuration file in order to configure the execution of your program.
This will need extra development since you will have to dynamicly change string. It's up to you.
*) Just test for the existence of "server.ini" or "client.ini" file.
Work if the two file don't exist at the same time.

iOS debugBlock macro

I'm sure alot of you are aware of the macro
#ifdef DEBUG
#define DebugLog( s, ... ) NSLog( #"<%p %#:(%d)> %#", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, [NSString stringWithFormat:(s), ##__VA_ARGS__] )
#else
#define DebugLog( s, ... )
#endif
This of course creates a function called DebugLog which you use in place of NSLog. Then when you change your project out of debug it will stop executing all of the NSLogs statements.
What I was thinking is is there a way to get this to work but with blocks. In other words I want to be able to do this:
DebugBlock(^{
//Code to only be executed while in Debug
});
Yes, I realize I can just do #ifdef DEBUG everywhere but that's not fancy enough for me :).
I feel kind of foolish about how simple it was but here is the solution.
#ifdef DEBUG
#define DebugBlock( ... ) dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ##__VA_ARGS__)
#else
#define DebugBlock( ... )
#endif
The the usage looks a little something like this:
DebugBlock(^{
int i = 12;
int b = 400;
int Answer = i+b;
NSLog(#"%d", Answer);
});
You can also change the dispatch type fo async if your heart desires.

c++ macro concatation not worked under gcc

#include <iostream>
void LOG_TRACE() { std::cout << "reach here"; }
#define LOG_LL_TRACE LOG_TRACE
#define LL_TRACE 0
#define __LOG(level) LOG_##level()
#define LOG(level) __LOG(##level)
int main()
{
LOG(LL_TRACE);
return 0;
}
The code is worked under Visual Studio, but report: test.cpp:13:1: error: pasting "(" and "LL_TRACE" does not give a valid preprocessing token.
How can I fix it?
ps: The macro expansion is supposed to be LOG(LL_TRACE) --> __LOG(LL_TRACE) --> LOG_LL_TRACE().
ps: suppose LL_TRACE must have a 0 value, do not remove it.
Two things make this code not compile on g++:
First, the error you're quoting is because you want to have this:
#define LOG(level) __LOG(level)
Notice no ##. Those hashmarks mean concatenate, but you're not concatenating anything. Just forwarding an argument.
The second error is that you have to remove
#define LL_TRACE 0
This line means you end up calling LOG(0) which expands into LOG_0 which isn't defined.
Shouldn't it be :
#define LOG(level) __LOG(level)
That works:
#include <iostream>
void LOG_TRACE() { std::cout << "reach here"; }
#define LOG_LL_TRACE LOG_TRACE
#define __LOG( level ) LOG_##level()
#define LOG(level) __LOG(level)
int main()
{
LOG( LL_TRACE );
return 0;
}

Can func get the lineno who call itself? (C/C++)

I've a problem , as the following code discribe itself.
1 #include<stdlib.h>
2 #include<stdio.h>
3 void log()
4 {
5 printf("Log [Line:%d]\n",__LINE__);
6 }
7 int main()
8 {
9 log();
10 log();
11 }
The expected result is
Log [Line:9]
Log [Line:10]
But, the fact is
Log [Line:5]
Log [Line:5]
No surprising, LINE has been substituted at the pre-process stage as 5.
My Question is, how to design the log function to get the expected result?
Thanks!
You need to write a macro:
#define LOG printf("Log [Line:%d]\n",__LINE__)
then use it:
int main() {
LOG;
LOG;
}
This works because the macro is expanded at its point of use, giving the __LINE__ macro the correct value.
A macro can overcome this, by passing in the __LINE__ as a parameter to the invoked function.
Another, perhaps complementary approach is to pass some context to the function as a parameter, with a default value that says 'use the line number'. This is illustrated by this code snippet which is doing error handling with the pattern:
int read_byte(FILE* f,int line=0) {
int ret = fgetc(f);
if(-1 == ret)
throw (line? line: __LINE__);
return ret;
}
int read_uint16(FILE* f,int line=0) {
int hi = read_byte(f,(line? line: __LINE__));
int lo = read_byte(f,(line? line: __LINE__));
return (hi<<8)|lo;
}
int main() {
...
try {
int i = read_uint16(f,__LINE__);
} catch(int line) {
fprintf(stderr,"Error at line %d\n",line);
}
...
}
Finally, this all smacks of wanting to get a stack trace out of C/C++ code (especially in the error handling cases). Look at VALGRIND_PRINTF_BACKTRACE(format, ...)
You can modify your existing function slightly, and wrap it in a macro:
#include<stdlib.h>
#include<stdio.h>
#define log() real_log(__LINE__)
void real_log(int line)
{
printf("Log [Line:%d]\n", line);
}
int main()
{
log();
log();
}

How do you create a debug only function that takes a variable argument list? Like printf()

I'd like to make a debug logging function with the same parameters as printf. But one that can be removed by the pre-processor during optimized builds.
For example:
Debug_Print("Warning: value %d > 3!\n", value);
I've looked at variadic macros but those aren't available on all platforms. gcc supports them, msvc does not.
I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax:
#include <stdio.h>
void XTrace0(LPCTSTR lpszText)
{
::OutputDebugString(lpszText);
}
void XTrace(LPCTSTR lpszFormat, ...)
{
va_list args;
va_start(args, lpszFormat);
int nBuf;
TCHAR szBuffer[512]; // get rid of this hard-coded buffer
nBuf = _vsnprintf(szBuffer, 511, lpszFormat, args);
::OutputDebugString(szBuffer);
va_end(args);
}
Then a typical #ifdef switch:
#ifdef _DEBUG
#define XTRACE XTrace
#else
#define XTRACE
#endif
Well that can be cleaned up quite a bit but it's the basic idea.
This is how I do debug print outs in C++. Define 'dout' (debug out) like this:
#ifdef DEBUG
#define dout cout
#else
#define dout 0 && cout
#endif
In the code I use 'dout' just like 'cout'.
dout << "in foobar with x= " << x << " and y= " << y << '\n';
If the preprocessor replaces 'dout' with '0 && cout' note that << has higher precedence than && and short-circuit evaluation of && makes the whole line evaluate to 0. Since the 0 is not used the compiler generates no code at all for that line.
Here's something that I do in C/C++. First off, you write a function that uses the varargs stuff (see the link in Stu's posting). Then do something like this:
int debug_printf( const char *fmt, ... );
#if defined( DEBUG )
#define DEBUG_PRINTF(x) debug_printf x
#else
#define DEBUG_PRINTF(x)
#endif
DEBUG_PRINTF(( "Format string that takes %s %s\n", "any number", "of args" ));
All you have to remember is to use double-parens when calling the debug function, and the whole line will get removed in non-DEBUG code.
Ah, vsprintf() was the thing I was missing. I can use this to pass the variable argument list directly to printf():
#include <stdarg.h>
#include <stdio.h>
void DBG_PrintImpl(char * format, ...)
{
char buffer[256];
va_list args;
va_start(args, format);
vsprintf(buffer, format, args);
printf("%s", buffer);
va_end(args);
}
Then wrap the whole thing in a macro.
Another fun way to stub out variadic functions is:
#define function sizeof
#CodingTheWheel:
There is one slight problem with your approach. Consider a call such as
XTRACE("x=%d", x);
This works fine in the debug build, but in the release build it will expand to:
("x=%d", x);
Which is perfectly legitimate C and will compile and usually run without side-effects but generates unnecessary code. The approach I usually use to eliminate that problem is:
Make the XTrace function return an int (just return 0, the return value doesn't matter)
Change the #define in the #else clause to:
0 && XTrace
Now the release version will expand to:
0 && XTrace("x=%d", x);
and any decent optimizer will throw away the whole thing since short-circuit evaluation would have prevented anything after the && from ever being executed.
Of course, just as I wrote that last sentence, I realized that perhaps the original form might be optimized away too and in the case of side effects, such as function calls passed as parameters to XTrace, it might be a better solution since it will make sure that debug and release versions will behave the same.
In C++ you can use the streaming operator to simplify things:
#if defined _DEBUG
class Trace
{
public:
static Trace &GetTrace () { static Trace trace; return trace; }
Trace &operator << (int value) { /* output int */ return *this; }
Trace &operator << (short value) { /* output short */ return *this; }
Trace &operator << (Trace &(*function)(Trace &trace)) { return function (*this); }
static Trace &Endl (Trace &trace) { /* write newline and flush output */ return trace; }
// and so on
};
#define TRACE(message) Trace::GetTrace () << message << Trace::Endl
#else
#define TRACE(message)
#endif
and use it like:
void Function (int param1, short param2)
{
TRACE ("param1 = " << param1 << ", param2 = " << param2);
}
You can then implement customised trace output for classes in much the same way you would do it for outputting to std::cout.
What platforms are they not available on? stdarg is part of the standard library:
http://www.opengroup.org/onlinepubs/009695399/basedefs/stdarg.h.html
Any platform not providing it is not a standard C implementation (or very, very old). For those, you will have to use varargs:
http://opengroup.org/onlinepubs/007908775/xsh/varargs.h.html
Part of the problem with this kind of functionality is that often it requires
variadic macros. These were standardized fairly recently(C99), and lots of
old C compilers do not support the standard, or have their own special work
around.
Below is a debug header I wrote that has several cool features:
Supports C99 and C89 syntax for debug macros
Enable/Disable output based on function argument
Output to file descriptor(file io)
Note: For some reason I had some slight code formatting problems.
#ifndef _DEBUG_H_
#define _DEBUG_H_
#if HAVE_CONFIG_H
#include "config.h"
#endif
#include "stdarg.h"
#include "stdio.h"
#define ENABLE 1
#define DISABLE 0
extern FILE* debug_fd;
int debug_file_init(char *file);
int debug_file_close(void);
#if HAVE_C99
#define PRINT(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, format, ##__VA_ARGS__); \
} \
else { \
fprintf(stdout, format, ##__VA_ARGS__); \
} \
}
#else
void PRINT(int enable, char *fmt, ...);
#endif
#if _DEBUG
#if HAVE_C99
#define DEBUG(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, "%s : %d " format, __FILE__, __LINE__, ##__VA_ARGS__); \
} \
else { \
fprintf(stderr, "%s : %d " format, __FILE__, __LINE__, ##__VA_ARGS__); \
} \
}
#define DEBUGPRINT(x, format, ...) \
if ( x ) { \
if ( debug_fd != NULL ) { \
fprintf(debug_fd, format, ##__VA_ARGS__); \
} \
else { \
fprintf(stderr, format, ##__VA_ARGS__); \
} \
}
#else /* HAVE_C99 */
void DEBUG(int enable, char *fmt, ...);
void DEBUGPRINT(int enable, char *fmt, ...);
#endif /* HAVE_C99 */
#else /* _DEBUG */
#define DEBUG(x, format, ...)
#define DEBUGPRINT(x, format, ...)
#endif /* _DEBUG */
#endif /* _DEBUG_H_ */
Have a look at this thread:
How to make a variadic macro (variable number of arguments)
It should answer your question.
This is what I use:
inline void DPRINTF(int level, char *format, ...)
{
# ifdef _DEBUG_LOG
va_list args;
va_start(args, format);
if(debugPrint & level) {
vfprintf(stdout, format, args);
}
va_end(args);
# endif /* _DEBUG_LOG */
}
which costs absolutely nothing at run-time when the _DEBUG_LOG flag is turned off.
This is a TCHAR version of user's answer, so it will work as ASCII (normal), or Unicode mode (more or less).
#define DEBUG_OUT( fmt, ...) DEBUG_OUT_TCHAR( \
TEXT(##fmt), ##__VA_ARGS__ )
#define DEBUG_OUT_TCHAR( fmt, ...) \
Trace( TEXT("[DEBUG]") #fmt, \
##__VA_ARGS__ )
void Trace(LPCTSTR format, ...)
{
LPTSTR OutputBuf;
OutputBuf = (LPTSTR)LocalAlloc(LMEM_ZEROINIT, \
(size_t)(4096 * sizeof(TCHAR)));
va_list args;
va_start(args, format);
int nBuf;
_vstprintf_s(OutputBuf, 4095, format, args);
::OutputDebugString(OutputBuf);
va_end(args);
LocalFree(OutputBuf); // tyvm #sam shaw
}
I say, "more or less", because it won't automatically convert ASCII string arguments to WCHAR, but it should get you out of most Unicode scrapes without having to worry about wrapping the format string in TEXT() or preceding it with L.
Largely derived from MSDN: Retrieving the Last-Error Code
Not exactly what's asked in the question . But this code will be helpful for debugging purposes , it will print each variable's value along with it's name . This is completely type independent and supports variable number of arguments.
And can even display values of STL's nicely , given that you overload output operator for them
#define show(args...) describe(#args,args);
template<typename T>
void describe(string var_name,T value)
{
clog<<var_name<<" = "<<value<<" ";
}
template<typename T,typename... Args>
void describe(string var_names,T value,Args... args)
{
string::size_type pos = var_names.find(',');
string name = var_names.substr(0,pos);
var_names = var_names.substr(pos+1);
clog<<name<<" = "<<value<<" | ";
describe(var_names,args...);
}
Sample Use :
int main()
{
string a;
int b;
double c;
a="string here";
b = 7;
c= 3.14;
show(a,b,c);
}
Output :
a = string here | b = 7 | c = 3.14
Having come across the problem today, my solution is the following macro:
static TCHAR __DEBUG_BUF[1024];
#define DLog(fmt, ...) swprintf(__DEBUG_BUF, fmt, ##__VA_ARGS__); OutputDebugString(__DEBUG_BUF);
You can then call the function like this:
int value = 42;
DLog(L"The answer is: %d\n", value);