Home > Mobile >  How to print the current filename with a function defined in another file?
How to print the current filename with a function defined in another file?

Time:11-08

Is it possible to print the caller source file name calling a function defined in another file, without passing __FILE__ explicitly and without using preprocessor tricks?

// Header.h

#include <iostream>
#include <string>
using namespace std;

void Log1(string msg) {
   cout << __FILE__ << msg << endl;   // this prints "Header.h"
}

void Log2(string file, string msg) {
   cout << file << msg << endl;
}

inline void Log3(string msg) {
   cout << __FILE__ << msg << endl;   // this prints "Header.h"
}


// Source.cpp

#include "Header.h"

int main()
{    
    Log1(" Test 1");
    Log2(__FILE__, " Test 2");
    Log3(" Test 3");
}

With this code, this is what I get:

pathTo\Header.h Test 1
pathTo\Source.cpp Test 2
pathTo\Header.h Test 3

I would have expected the last call to print: pathTo\Source.cpp Test 3

CodePudding user response:

You could use std::source_location:

// library.h
#pragma once
#include <source_location>
#include <string>

void Log(std::string msg, const std::source_location loc =
                                std::source_location::current());
// library.cpp
#include "library.h"
#include <iostream>

void Log(std::string msg, const std::source_location loc) {
    std::cout << loc.file_name() << ' '<< msg << '\n';
}
// Source.cpp
#include "library.h"

int main() {    
    Log("Test 1"); // Prints "Source.cpp Test 1"
}

This requires C 20. Prior to C 20 you can use boost::source_location.

  • Related