如何获取当前源路径在C ++ - Linux [英] How to get current source path in C++ - Linux
问题描述
我想要能够获取当前的源文件路径。
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());
有办法获得CURRENT_FILE_PATH吗?
我不是指可执行路径。我的意思是代码运行的源文件的当前位置。
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.
非常感谢,
Giora。
Thanks a lot, Giora.
推荐答案
用于编译源文件的路径可通过标准C宏 __ FILE __
=http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html =nofollow> http://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros。 html )
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)
如果你给绝对路径作为编译器的输入(至少对于gcc) __ FILE __
将保存文件的绝对路径,反之亦然。
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.
如果您使用GNU Make,并在变量 SOURCE_FILES
中列出源文件,像这样:
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 ...)
这篇关于如何获取当前源路径在C ++ - Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!