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

后端 未结 2 1556
我在风中等你
我在风中等你 2020-12-10 15:30

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());
         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-10 16:17

    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 ...)
    

提交回复
热议问题