Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

I want to be able to get the current source file path.

string txt_file = CURRENT_FILE_PATH +"../../txt_files/first.txt";
inFile.open(txt_file .c_str());

Is there a way to get the CURRENT_FILE_PATH ? I don't mean the executable path. I mean the current location of the source file that the code is running from.

Thanks a lot, Giora.

like image 711
gioravered Avatar asked Dec 05 '13 07:12

gioravered


2 Answers

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 ...)
like image 63
Robert Jørgensgaard Engdahl Avatar answered Oct 19 '22 11:10

Robert Jørgensgaard Engdahl


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!