如何在C++-Linux中获取当前源路径

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

本文关键字:路径 获取 C++-Linux      更新时间:2023-10-16

我希望能够获得当前的源文件路径。

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

有没有办法获得CURRENT_FILE_PATH?我不是指可执行路径。我指的是运行代码的源文件的当前位置。

非常感谢,Giora。

C++20 source_location::file_name

除了__FILE__,我们现在还有另一种方法,不使用旧的C预处理器:http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf

文件只是简单地说:

constexpr const char*file_name()const noexcept;

5返回:当前源文件(14.2)的假定名称通过该对象作为NTBS。

其中NTBS表示"空终止字节串"。

当支持到达GCC时,我会尝试一下,带有g++-9 -std=c++2a的GCC 9.1.0仍然不支持它。

https://en.cppreference.com/w/cpp/utility/source_location声明使用情况如下:

#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!");
}

可能输出:

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

用于编译源文件的路径可通过标准C宏__FILE__访问(请参阅http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html)

如果给编译器一个绝对路径作为输入(至少对于gcc),__FILE__将保存文件的绝对路径,相对路径则相反。其他编译器可能略有不同。

如果你正在使用GNUMake,并且你在变量SOURCE_FILES中列出了你的源文件,如下所示:

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

你可以确保文件是由它们的绝对路径给定的,如下所示:

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