How to print the current filename with a function defined in another file without using macros? [duplicate]
Asked Answered
D

1

12

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

Dinnie answered 7/11, 2022 at 11:23 Comment(3)
I think you're misunderstanding inline. It means "there can be multiple definitions in multiple Translation Units". That means it's intended for the linker. The preprocessor doesn't even notice the token.Knave
Dupe: What advantages does C++20's std::source_location have over the pre-defined macros FILE, LINE and FUNCTION?Convolve
Refer to how to ask where the first step is to "search and then research" and you'll find plenty of related SO posts for this.Convolve
R
17

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.

Refugia answered 7/11, 2022 at 11:30 Comment(3)
This is just what I was looking for. The only issue is that it requires C++20, which I cannot use, yet, because of project requirements... Please, let me know if anything with C++17 exists, otherwise I will accept your answer.Dinnie
@Dinnie I added a note about the requirement and a possible way to get very similar functionality in C++17.Refugia
Wow, such a magic is now available in C++!Dunagan

© 2022 - 2024 — McMap. All rights reserved.