如何在C++-Linux中获取当前源路径
How to get current source path in C++ - Linux
我希望能够获得当前的源文件路径。
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 ...)
相关文章:
- 从 GUID 获取 USB 卷路径
- 获取当前正在运行的 exe 名称(不是路径)
- 如何从 Skia 路径几何体中获取网格?
- 从 C 中的变量获取文件的路径,C++
- 获取 H5::D ataSet 的hid_t和文件中的路径以使用 H5OCopy
- 如何获取 CMake 单元测试的相对路径?
- 如何获取当前用户的默认RAS电话簿路径?
- 我应该如何获取配置文件的绝对路径与 Windows .exe一起发布?
- 获取每个目录或子目录中第一个文件的路径
- 如何自动获取我的项目的路径并删除一些文件
- 获取 JAR 文件中二进制文件的路径
- 如何使用提升获取当前文件路径?
- 如何在 c++ 中获取当前文件路径?
- 无法获取进程 ID 4 (ntoskrnl.exe) 的可执行路径
- 有没有一种简单的方法可以从 c++ 中的路径获取文件名?
- 运行正则表达式时未选中的异常 - 从文件路径获取不带扩展名的文件名
- POSIX 或 Linux API 函数,用于从路径获取文件扩展名
- 通过路径获取 Windows 可执行文件的显示名称
- 从USB设备的设备路径获取卷名
- 如何从其路径获取进程PID