Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the caller __FILE__ __LINE__ to a function without using macro

Tags:

I'm used to this:

class Db {   _Commit(char *file, int line) {     Log("Commit called from %s:%d", file, line);   } };  #define Commit() _Commit(__FILE__, __LINE__) 

but the big problem is that I redefine the word Commit globally, and in a 400k lines application framework it's a problem. And I don't want to use a specific word like DbCommit: I dislike redundancies like db->DbCommit(), or to pass the values manually everywhere: db->Commit(__FILE__, __LINE__) is worst.

So, any advice?

like image 817
Nicola Leoni Avatar asked Nov 16 '10 16:11

Nicola Leoni


People also ask

What is __ LINE __ in C++?

__LINE__ is a preprocessor macro that expands to current line number in the source file, as an integer. __LINE__ is useful when generating log statements, error messages intended for programmers, when throwing exceptions, or when writing debugging code.

Can we call a macro function?

Just type the word Call then space, then type the name of the macro to be called (run). The example below shows how to call Macro2 from Macro1. It's important to note that the two macros DO NOT run at the same time.

How do I print line numbers in CPP?

Using __LINE__ Macro The standard solution to find the current line number in C++ is using the predefined macro __LINE__ . It returns the integer value representing the current line in the source code file being compiled.


1 Answers

So, you're looking to do logging (or something) with file & line info, and you would rather not use macros, right?

At the end of the day, it simply can't be done in C++. No matter what mechanism you chose -- be that inline functions, templates, default parameters, or something else -- if you don't use a macro, you'll simply end up with the filename & linenumber of the logging function, rather than the call point.

Use macros. This is one place where they are really not replaceable.

EDIT:

Even the C++ FAQ says that macros are sometimes the lesser of two evils.

EDIT2:

As Nathon says in the comments below, in cases where you do use macros, it's best to be explicit about it. Give your macros macro-y names, like COMMIT() rather than Commit(). This will make it clear to maintainers & debuggers that there's a macro call going on, and it should help in most cases to avoid collisions. Both good things.

like image 89
John Dibling Avatar answered Oct 28 '22 14:10

John Dibling