Some Name
Some Name

Reputation: 9540

Tracing static inline function

I'm trying to add some debugging facility to my application and now stuck with using static inline function. As I learnt from this answer it was possible to put static inline function definition into a header file so function is not instantiated twice in case the file is included multiple times.

So I was curious and tried to define the similar static inline function for tracing invokation and put it into a header file:

#ifndef TRACE_H
#define TRACE_H

static inline void trace(){
    printf("Current line %d, func %s, file %s\n", __LINE__, __func__, __FILE__);
}

#endif //TRACE_H

I tried this because static inline is much less error-prone then macro. The problem is that the simple

int main(int argc, char const *argv[])
{
    trace(); 
}

prints Current line 8, func trace, file /home/somename/include/trace.h which is obviously useless.

So for tracing purpose is there any other way unless to define the macro

#define trace() \
    printf("Current line %d, func %s, file %s\n", __LINE__, __func__, __FILE__); \

Upvotes: 1

Views: 523

Answers (1)

David Ranieri
David Ranieri

Reputation: 41046

I tried this because static inline is much less error-prone then macro.

Macros are dangerous when used with parameters that could be evaluated twice:

#define min(a, b) ((a) < (b)) ? (a) : (b)

But this is not the case.

The only workaround I can see is:

#define SOURCE __LINE__, __func__, __FILE__

static inline void trace(int line, const char *func, const char *file)
{
    printf("Current line %d, func %s, file %s\n", line, func, file);
}

int main(void)
{
    trace(SOURCE);
    ...

But still using the preprocessor.

Upvotes: 2

Related Questions