Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading