How to get current source path in C++ - Linux

C++20 source_location::file_name

We now have another way besides __FILE__, without using the old C preprocessor: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf

The documentation simply says:

constexpr const char* file_name() const noexcept;

5 Returns: The presumed name of the current source file (14.2) represented by this object as an NTBS.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>

void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}

int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

The path used to compile the source file is accessible through the standard C macro __FILE__ (see http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html)

If you give an absolute path as input to your compiler (at least for gcc) __FILE__ will hold the absolute path of the file, and vice versa for relative paths. Other compilers may differ slightly.

If you are using GNU Make and you list your source files in the variable SOURCE_FILES like so:

SOURCE_FILES := src/file1.cpp src/file2.cpp ...

you can make sure the files are given by their absolute path like so:

SOURCE_FILES := $(abspath src/file1.cpp src/file2.cpp ...)

Tags:

C++