I'm writing some libraries for a microcontroller, and for that purpose, I use macro-like functions. For example, a macro-like function to enable an I2C module is defined as:
#define I2C_MODULE_ENABLE(_x) \
I2C##_x##CONLbits.I2CEN = 1
where _x is the module number (e.g.,1 or 2 in my case).
If a user calls this macro-like function as I2C_MODULE_ENABLE(1), it would be expanded by a preprocessor as I2C1CONLbits. I2CEN = 1.
However, if a user calls this macro-like function as I2C_MODULE_ENABLE(MY_I2C), where MY_I2C is a macro constant defined in a user-defined config.h file that is included by my i2c.h library (e.g., the macro constant is defined as #define MY_I2C 1), the macro-like function would be expanded as I2CMY_I2CCONLbits. I2CEN = 1.
I know that I need to somehow evaluate the MY_I2C macro constant before concatenation, and I can do that by adding another macro level:
#define __I2CxCONLbits(_x) I2C##_x##CONLbits
#define I2C_MODULE_ENABLE(_x) \
__I2CxCONLbits.I2CEN = 1
My question is: is there a more elegant solution to this problem since I have multiple registers like the CONLbits register. Using this approach I would need to define a special __I2CxREGISTER(_x) macro for every register.
I tried to do something like this:
#define __I2Cx(_x) I2C##_x
#define I2C_MODULE_ENABLE(_x) \
__I2Cx(_x)##CONLbits.I2CEN = 1
but that produces an output like this: I2C1 CONLbits .I2CEN = 1, and my compiler is complaining about the whitespace between I2C1 and CONLbits tokens.
You aren't adding the macro level properly, as I see it. The usual idiom is to define a wrapper that does nothing but forward the argument. That way, if the argument is itself a macro, it will be expanded before being passed to the macro that is wrapped:
#define I2C_MODULE_ENABLE__(x_) \
I2C##x_##CONLbits.I2CEN = 1
#define I2C_MODULE_ENABLE(x_) \
I2C_MODULE_ENABLE__(x_)
I took the liberty of renaming your macro parameter, since identifiers with leading underscores are defined as reserved for the implementation, I think it's better to be safe than sorry.
To solve your problem of the space I'd go with the proverbial level of indirection, and use a function like macro to generate the correct prefix token, and pass it along two levels to make sure it's expanded correctly:
#define I2Cx__(x_) I2C##x_
#define I2C_MODULE_ENABLE__(IC_) \
IC_##CONLbits.I2CEN = 1
#define I2C_MODULE_ENABLE_(IC_) \
I2C_MODULE_ENABLE__(IC_)
#define I2C_MODULE_ENABLE(x_) \
I2C_MODULE_ENABLE_(I2Cx__(x_))
See it live here
The whole shtick is to make sure the preprocessor sees and produces valid tokens at each step. Which can be a bit tiresome.
Related
In a sketch I found the following instruction:
#define USB_CONFIG_POWER_MA(mA) ((mA)/2)
And I want to be sure not to make any mistake: why are there two "mA"?
Which one should I replace by a value given that in a previous version of this code one just needed this line:
#define USB_CONFIG_POWER_MA(20)
to set the max to 20mA but now it gives a compilation error:
/home/henry/arduino-1.8.16/hardware/arduino/avr/cores/arduino/USBCore.h:99:29: error: "20" may not appear in macro parameter list
This seems to be the solution as it gives me no compilation error
#define USB_CONFIG_POWER_MA(mA) ((40)/2)
but again i want to be sure!
With
#define USB_CONFIG_POWER_MA(mA) ((mA)/2)
you define a function-like macro, where mA is the argument to the macro.
You can use it like:
printf("USB power for 20 mA is %d\n", USB_CONFIG_POWER_MA(20));
The preprocessor will replace the macro as such:
printf("USB power for 20 mA is %d\n", ((20)/2));
If you always want the macro to be replaced by the value 20 then either define a function-like macro where you ignore the argument (this will be backward compatible):
#define USB_CONFIG_POWER_MA(mA) 20
Or define a macro without arguments (this will require you to change all macro invocations):
#define USB_CONFIG_POWER_MA 20
The latter, without arguments, is often used in C as a way to define symbolic constants, and as such makes more sense in your use-case.
Another possible solution is to use the original macro definition, but use a second macro to define the value to pass as argument:
#define USB_CONFIG_POWER_MA(mA) ((mA)/2)
#define USB_CONFIG_DEFAULT_POWER 40
// ...
printf("USB power for 20 mA is %d\n",
USB_CONFIG_POWER_MA(USB_CONFIG_DEFAULT_POWER));
This will both be backward compatible and allow other values to be used together with the original USB_CONFIG_POWER_MA macro.
to set the max to 20mA
You shouldn't change the definition of the USB_CONFIG_POWER_MA macro, you should change the value that's passed to it where it's used. The macro you're talking about comes from USBCore.h:
#define D_CONFIG(_totalLength,_interfaces) \
{ 9, 2, _totalLength,_interfaces, 1, 0, \
USB_CONFIG_BUS_POWERED | USB_CONFIG_REMOTE_WAKEUP, \
USB_CONFIG_POWER_MA(USB_CONFIG_POWER) }
You can see the macro being used to set the configured power here. Looking deeper, the definition of USB_CONFIG_POWER is:
#ifndef USB_CONFIG_POWER
#define USB_CONFIG_POWER (500)
#endif
So USB_CONFIG_POWER only gets defined if it isn't already defined. That means that all you need to do to set the power that your Arduino sketch requests is to make sure that you define USB_CONFIG_POWER yourself before you include the USBCore.h file. Put a line like:
#define USB_CONFIG_POWER (20)
in your code before you include that file, and you should be good to go.
I'm trying to make my header file easily changeable with macros. I'm debugging my code and it seems these MACROS are not doing what they are supposed to. Can someone tell me how I achieve the following effect? LED_ID_AMS etc.
#define LED_NUMBER (2)
#define LED_ID_X (0)
#define LED_ID_Y (1)
#define LED_PIN_X (0)
#define LED_PIN_Y (3)
#define LED_PORT_X (PORTE)
#define LED_PORT_Y (PORTG)
#define LED_DD_X (DDRE)
#define LED_DD_Y (DDRG)
#define LED_PORT(LED_ID_X) (LED_PORT_X)
#define LED_PORT(LED_ID_Y) (LED_PORT_Y)
#define LED_PIN(LED_ID_X) (LED_PIN_X)
#define LED_PIN(LED_ID_Y) (LED_PIN_Y)
#define LED_DD(LED_ID_X) (LED_DD_X)
#define LED_DD(LED_ID_Y) (LED_DD_Y)
What am I trying to achieve?
I'm trying to make it so I can loop through the port init like so:
for(i=0;i<LED_NUMBER;i++){
/* set data direction to output*/
LED_DD(i)|=((0x01)<<LED_PIN(i));
/* turn on led */
LED_PORT(i)|=((0x01)<<LED_PIN(i));
}
You will regret using too many macros later. Actually, you're regretting it already, as they don't work and, being macros, they are very difficult to debug.
Just a few points:
your LED_PIN(i) expressions are always expanding to 0
your LED_PORT(i) expressions are always expanding to PORTE whatever that may be
For instance LED_PIN(LED_ID_X) expands to LED_PIN_X. Note, macro parameter LED_ID_X is not used at all. Instead, LED_PIN_X simply expands to 0.
This should scream warnings at you, as e.g. LED_PORT(SOME_ARG) has several definitions. And in LED_PORT(LED_ID_X) the LED_ID_X is just a dummy argument, with absolutely no relation to your constant LED_ID_X.
You can make your code equally readable by using a constant array, perhaps used from macros like you try to do here.
Unless there are a massive number of LED_ID_<foo>, this is at best a minor simplification. Don't do that. If there is a lot of code futzing around with those is mostly the same way, it might make sense to define a macro that iterates some action over each of them, i.e.:
#define FROB_LEDS \\
action(LED_ID_X); \\
action(LED_ID_Y); \\
action(LED_ID_Z);
and define action(X) locally as a macro to do the action on LED X, FROB them, and undefine action again. Quite ugly, true.
You'll have to add at least one of:
arrays
inline functions
more complicated macros
And it also seems to me that dereferencing of hardware addresses will be required.
For example, using macros, you can define:
#define LED_PORT(i) *(uint16_t *)( \
(i) == LED_ID_X ? LED_PORT_X : \
(i) == LED_ID_Y ? LED_PORT_Y : \
etc)
where:
#define LED_ID_X (0)
#define LED_ID_Y (1)
#define LED_PORT_X (PORTE)
#define LED_PORT_Y (PORTG)
#define PORTE (0x11112222U) // example only
#define PORTG (0x33334444U) // example only
Here uint16_t is only a guess: I'm assuming 16-bit ports in a 32-bit address space.
Or, using arrays and C99's designated initializers:
const uint32_t LED_PORT[] = {
[LED_ID_X] = LED_PORT_X,
[LED_ID_Y] = LED_PORT_Y
};
#define LED_PORT(i) (*(uint16_t *)LED_PORT[i])
And of course, without C99 you can use just:
const uint32_t LED_PORT[] = {LED_PORT_X, LED_PORT_Y};
which assumes that LED_ID_X is 0, etc.
I am attempting to make a section of code a bit more generic for a microcontroller that I am currently programming for.
What I want is a specific macro, formed from other tokens via concatenation. The problem is that one of the tokens is defined as a specific memory address (i.e. a register) and thus "garbage" is substituted mid-way. The following snippet illustrates the problem:
#include <stdio.h>
#include <stdint.h>
// The actual final token that I want (because I want the value of 10)
#define I_DRINK_BEER 10
// This line is the problematic line!
// It us defined in the microcontroller-specific header
// If this line is not defined, it works perfectly as desired.
#define DRINK (*(uint32_t*) (0x8000))
#define ACTION DRINK
#define INDIRECT(who,action,what) who ## action ## what
#define TOKEN_PASTE(who,action,what) INDIRECT(who,action,what)
#define CONSUMPTION(who,what) TOKEN_PASTE(who,ACTION,what)
int main(void)
{
printf("Value = %d\n", CONSUMPTION(I_,_BEER));
return 0;
}
If the line "#define DRINK ..." is commented out, the program compiles and executes as desired:
damien#damien-desktop:~$ gcc -o test test_macro_expansion.c
damien#damien-desktop:~$ ./test
Value = 10
But the inclusion of the offending line substitutes the complete address that makes the pre-processor complain:
test_macro_expansion.c: In function ‘main’:
test_macro_expansion.c:21:1: error: pasting "I_" and "(" does not give a valid preprocessing token
test_macro_expansion.c:21:1: error: pasting ")" and "_BEER" does not give a valid preprocessing token
test_macro_expansion.c:21:28: error: expected ‘)’ before ‘_BEER’
Is there a way I can tell the pre-processor not to substitute a particular token any further?
Why??
Before this seems a little esoteric, I have a timer for some particular functionality that is assigned to timer/counter "TCC0" in one project and "TCD1" in another project. It happens to be defined in as the base address of the register block for each timer, respectively. So, I have in my config header:
#define PERIPHERAL_TIMER TCC0
Which, works well in the main, because the registers of the timer can be referenced easily, for example:
value = PERIPHERAL_TIMER.CCA;
Deep in the toolchain, TCC0 is defined:
#define TCC0 (*(TC0_t *) 0x0800) /* Timer/Counter C0 */
The problem is that I have other macros defined in that have the TCC0) as part of the the name that I need elsewhere, for example:
// Note the TCC0 in the function argument!
EventSystem_SetEventSource(EVSYS_CHMUX_TCC0_OVF_gc);
Hence, I would like to define the symbol
// Conceptually what I want!
#define EVENT_SOURCE(timer) EVSYS_CHMUX_ ## timer ## _OVF_gc
// The "PERIPHERAL_TIMER" gets expanded to the address, not the token that I want
#define PERIPHERAL_EVENT EVENT_SOURCE(PERIPHERAL_TIMER)
I hope this clears up why I am asking the question.
#define DRINK (*(uint32_t) (0x8000)). this line has an error which is as UNDEFINED Symbol uint .
Well, the simplest, easiest workaround that solves this particular issue is:
// It was this...
// #define PERIPHERAL_TIMER TCC0
// And is now this
#define PERIPHERAL_TIMER_SUFFIX C0
So the macros can be easily defined:
// Conceptually what I want - modified, but be sure to use
// indirect substitution as required.
#define EVENT_SOURCE(timer) EVSYS_CHMUX_TC ## timer ## _OVF_gc
And PERIPHERAL_TIMER can still be defined for direct register access:
// Don't forget, you'll need to use indirect substitution
#define PERIPHERAL_TIMER TC ## PERIPHERAL_TIMER_SUFFIX
// Registers can still be access as:
value = PERIPHERAL_TIMER.CCA;
NOTE: Indirect substitution in this post refers to the technique in this answer.
I am hoping that someone may have an idea on how to control/specify the order of macro expansion. Here is the context:
// 32 bit increments, processor has registers for set, clear and invert
#define CLR_OFF 1
#define SET_OFF 2
#define INV_OFF 3
#define SET(reg,bits) *((volatile unsigned long*)(& reg+SET_OFF)) = bits
//Now if I use this I can do it quite nicely with
#define STATUS_LED 0x0040;
SET(LATB, STATUS_LED); // LATB is port of the LED.
I've actually had to move hardware around quite a bit as of late so I decided to group the LATB info with the STATUS_LED like so...
#define STATUS_LED_PORT LATB
#define STATUS_LED_MASK 0x0040;
#define STATUS_LED STATUS_LED_PORT, STATUS_LED_MASK
//And I try to use it via
SET( STATUS_LED );
But alas, LATB,0x0040 is passed to argument 1 of the SET macro. When not used as a macro this method works properly:
inline void SET(u32_t *reg, u32_t bits) { ((volatile u32_t *) (((u32_t)reg) + SET_OFF*4 )) = bits; }
//Change the STATUS_LED macro to
#define STATUS_LED &STATUS_LED_PORT, STATUS_LED_MASK
SET( STATUS_LED); //Works great!
But unfortunately my compiler doesn't see the need to inline the function and causes 6 instructions to set the register as opposed to 4, so for use while bit-banging it is unpredictable.
I am hoping someone may know of a way to expand the STATUS_LED macro first, something like:
SET( ##STATUS_LED )
Currently my solution to move on is to have two macros SET, and SETRM (set register, mask) but I feel like there should be a solution because the code for SET looks like...
#define SETRM(reg,bits) ...
#define SET(args) SETRM(args) //WHY WOULD THIS GET EXPANDED HERE??
And lastly, my processor's compiler does not support n-arguments to a macro, I thought I might be able to play with that but alas :(.
Thank you very much for your time, and I would appreciate any thoughts, I can move forward, but it would be so much cleaner if I could just use SET everywhere.
Substitution of parameters in the expansion of function-like macros happens in a set way. All arguments which don't appear after the # operator or either side of a ## are fully macro expanded when they are replaced, not before the function-like macro is expanded.
This means that to make a single macro become two macro arguments a round of macro substitution must occur before the required function like macro is itself expanded.
This means that the solution of a second function like macro that expands to the desired function-like macro is the simplest solution.
i.e. given your original SET definition
#define SET(reg,bits) *((volatile unsigned long*)(& reg+SET_OFF)) = bits
and a macro that expands to two potential arguments
#define STATUS_LED_PORT LATB
#define STATUS_LED_MASK 0x0040;
#define STATUS_LED STATUS_LED_PORT, STATUS_LED_MASK
You have to use another function-like macro to get the substitution that you need.
e.g.
#define SET2(x) SET(x)
Then SET2( STATUS_LED ) expands as follows.
SET( LATB , 0x0040; )
then
*((volatile unsigned long*)(& LATB + 2 )) = 0x0040;
This isn't valid as there are not enough arguments to the SET macro; the parameters are matched to arguments before any expansion of the argument occurs. My compiler generates an error; the behaviour isn't defined.
SET( STATUS_LED )
If the root name is always the same you could use:
#define SET_COMPOSITE(root) SET(root##_PORT, root##_MASK)
As mentioned in many of my previous questions, I'm working through K&R, and am currently into the preprocessor. One of the more interesting things — something I never knew before from any of my prior attempts to learn C — is the ## preprocessor operator. According to K&R:
The preprocessor operator ##
provides a way to concatenate actual
arguments during macro expansion. If a
parameter in the replacement text is
adjacent to a ##, the parameter is
replaced by the actual argument, the
## and surrounding white space are
removed, and the result is re-scanned.
For example, the macro paste
concatenates its two arguments:
#define paste(front, back) front ## back
so paste(name, 1) creates the token
name1.
How and why would someone use this in the real world? What are practical examples of its use, and are there gotchas to consider?
One thing to be aware of when you're using the token-paste ('##') or stringizing ('#') preprocessing operators is that you have to use an extra level of indirection for them to work properly in all cases.
If you don't do this and the items passed to the token-pasting operator are macros themselves, you'll get results that are probably not what you want:
#include <stdio.h>
#define STRINGIFY2( x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#define PASTE2( a, b) a##b
#define PASTE( a, b) PASTE2( a, b)
#define BAD_PASTE(x,y) x##y
#define BAD_STRINGIFY(x) #x
#define SOME_MACRO function_name
int main()
{
printf( "buggy results:\n");
printf( "%s\n", STRINGIFY( BAD_PASTE( SOME_MACRO, __LINE__)));
printf( "%s\n", BAD_STRINGIFY( BAD_PASTE( SOME_MACRO, __LINE__)));
printf( "%s\n", BAD_STRINGIFY( PASTE( SOME_MACRO, __LINE__)));
printf( "\n" "desired result:\n");
printf( "%s\n", STRINGIFY( PASTE( SOME_MACRO, __LINE__)));
}
The output:
buggy results:
SOME_MACRO__LINE__
BAD_PASTE( SOME_MACRO, __LINE__)
PASTE( SOME_MACRO, __LINE__)
desired result:
function_name21
CrashRpt: Using ## to convert macro multi-byte strings to Unicode
An interesting usage in CrashRpt (crash reporting library) is the following:
#define WIDEN2(x) L ## x
#define WIDEN(x) WIDEN2(x)
//Note you need a WIDEN2 so that __DATE__ will evaluate first.
Here they want to use a two-byte string instead of a one-byte-per-char string. This probably looks like it is really pointless, but they do it for a good reason.
std::wstring BuildDate = std::wstring(WIDEN(__DATE__)) + L" " + WIDEN(__TIME__);
They use it with another macro that returns a string with the date and time.
Putting L next to a __ DATE __ would give you a compiling error.
Windows: Using ## for generic Unicode or multi-byte strings
Windows uses something like the following:
#ifdef _UNICODE
#define _T(x) L ## x
#else
#define _T(x) x
#endif
And _T is used everywhere in code
Various libraries, using for clean accessor and modifier names:
I've also seen it used in code to define accessors and modifiers:
#define MYLIB_ACCESSOR(name) (Get##name)
#define MYLIB_MODIFIER(name) (Set##name)
Likewise you can use this same method for any other types of clever name creation.
Various libraries, using it to make several variable declarations at once:
#define CREATE_3_VARS(name) name##1, name##2, name##3
int CREATE_3_VARS(myInts);
myInts1 = 13;
myInts2 = 19;
myInts3 = 77;
Here's a gotcha that I ran into when upgrading to a new version of a compiler:
Unnecessary use of the token-pasting operator (##) is non-portable and may generate undesired whitespace, warnings, or errors.
When the result of the token-pasting operator is not a valid preprocessor token, the token-pasting operator is unnecessary and possibly harmful.
For example, one might try to build string literals at compile time using the token-pasting operator:
#define STRINGIFY(x) #x
#define PLUS(a, b) STRINGIFY(a##+##b)
#define NS(a, b) STRINGIFY(a##::##b)
printf("%s %s\n", PLUS(1,2), NS(std,vector));
On some compilers, this will output the expected result:
1+2 std::vector
On other compilers, this will include undesired whitespace:
1 + 2 std :: vector
Fairly modern versions of GCC (>=3.3 or so) will fail to compile this code:
foo.cpp:16:1: pasting "1" and "+" does not give a valid preprocessing token
foo.cpp:16:1: pasting "+" and "2" does not give a valid preprocessing token
foo.cpp:16:1: pasting "std" and "::" does not give a valid preprocessing token
foo.cpp:16:1: pasting "::" and "vector" does not give a valid preprocessing token
The solution is to omit the token-pasting operator when concatenating preprocessor tokens to C/C++ operators:
#define STRINGIFY(x) #x
#define PLUS(a, b) STRINGIFY(a+b)
#define NS(a, b) STRINGIFY(a::b)
printf("%s %s\n", PLUS(1,2), NS(std,vector));
The GCC CPP documentation chapter on concatenation has more useful information on the token-pasting operator.
This is useful in all kinds of situations in order not to repeat yourself needlessly. The following is an example from the Emacs source code. We would like to load a number of functions from a library. The function "foo" should be assigned to fn_foo, and so on. We define the following macro:
#define LOAD_IMGLIB_FN(lib,func) { \
fn_##func = (void *) GetProcAddress (lib, #func); \
if (!fn_##func) return 0; \
}
We can then use it:
LOAD_IMGLIB_FN (library, XpmFreeAttributes);
LOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);
LOAD_IMGLIB_FN (library, XpmReadFileToImage);
LOAD_IMGLIB_FN (library, XImageFree);
The benefit is not having to write both fn_XpmFreeAttributes and "XpmFreeAttributes" (and risk misspelling one of them).
A previous question on Stack Overflow asked for a smooth method of generating string representations for enumeration constants without a lot of error-prone retyping.
Link
My answer to that question showed how applying little preprocessor magic lets you define your enumeration like this (for example) ...;
ENUM_BEGIN( Color )
ENUM(RED),
ENUM(GREEN),
ENUM(BLUE)
ENUM_END( Color )
... With the benefit that the macro expansion not only defines the enumeration (in a .h file), it also defines a matching array of strings (in a .c file);
const char *ColorStringTable[] =
{
"RED",
"GREEN",
"BLUE"
};
The name of the string table comes from pasting the macro parameter (i.e. Color) to StringTable using the ## operator. Applications (tricks?) like this are where the # and ## operators are invaluable.
You can use token pasting when you need to concatenate macro parameters with something else.
It can be used for templates:
#define LINKED_LIST(A) struct list##_##A {\
A value; \
struct list##_##A *next; \
};
In this case LINKED_LIST(int) would give you
struct list_int {
int value;
struct list_int *next;
};
Similarly you can write a function template for list traversal.
The main use is when you have a naming convention and you want your macro to take advantage of that naming convention. Perhaps you have several families of methods: image_create(), image_activate(), and image_release() also file_create(), file_activate(), file_release(), and mobile_create(), mobile_activate() and mobile_release().
You could write a macro for handling object lifecycle:
#define LIFECYCLE(name, func) (struct name x = name##_create(); name##_activate(x); func(x); name##_release())
Of course, a sort of "minimal version of objects" is not the only sort of naming convention this applies to -- nearly the vast majority of naming conventions make use of a common sub-string to form the names. It could me function names (as above), or field names, variable names, or most anything else.
I use it in C programs to help correctly enforce the prototypes for a set of methods that must conform to some sort of calling convention. In a way, this can be used for poor man's object orientation in straight C:
SCREEN_HANDLER( activeCall )
expands to something like this:
STATUS activeCall_constructor( HANDLE *pInst )
STATUS activeCall_eventHandler( HANDLE *pInst, TOKEN *pEvent );
STATUS activeCall_destructor( HANDLE *pInst );
This enforces correct parameterization for all "derived" objects when you do:
SCREEN_HANDLER( activeCall )
SCREEN_HANDLER( ringingCall )
SCREEN_HANDLER( heldCall )
the above in your header files, etc. It is also useful for maintenance if you even happen to want to change the definitions and/or add methods to the "objects".
SGlib uses ## to basically fudge templates in C. Because there's no function overloading, ## is used to glue the type name into the names of the generated functions. If I had a list type called list_t, then I would get functions named like sglib_list_t_concat, and so on.
I use it for a home rolled assert on a non-standard C compiler for embedded:
#define ASSERT(exp) if(!(exp)){ \
print_to_rs232("Assert failed: " ## #exp );\
while(1){} //Let the watchdog kill us
I use it for adding custom prefixes to variables defined by macros. So something like:
UNITTEST(test_name)
expands to:
void __testframework_test_name ()
One important use in WinCE:
#define BITFMASK(bit_position) (((1U << (bit_position ## _WIDTH)) - 1) << (bit_position ## _LEFTSHIFT))
While defining register bit description we do following:
#define ADDR_LEFTSHIFT 0
#define ADDR_WIDTH 7
And while using BITFMASK, simply use:
BITFMASK(ADDR)
It is very useful for logging. You can do:
#define LOG(msg) log_msg(__function__, ## msg)
Or, if your compiler doesn't support function and func:
#define LOG(msg) log_msg(__file__, __line__, ## msg)
The above "functions" logs message and shows exactly which function logged a message.
My C++ syntax might be not quite correct.