3

This question is many time asked and I referred all, but I need bit different.

I am using macbook -> Clion (IDE) for C++ My program file location /Users/Kandarp/ClionProjects/SimulationParser/main.cpp

When I use following function for get current directory it gives different file (I think actual path where file is compiled and execute)

string ExePath() {
char cwd[1024];
if (getcwd(cwd, sizeof(cwd)) != NULL) {
    fprintf(stdout, "Current working dir: %s\n", cwd);
    return cwd;
} else {
    perror("getcwd() error");
    return 0;
}}

it gives following answer: /Users/Kandarp/Library/Caches/CLion2016.2/cmake/generated/SimulationParser-50b8dc0e/50b8dc0e/Debug

But I need path where my .cpp file reside.What I am doing wrong ? Please help

ildjarn
  • 62,044
  • 9
  • 127
  • 211
kandarp
  • 991
  • 1
  • 14
  • 35
  • 3
    C++ is a language used for real programs - programs that can be running on a million computers all over the world. Why would your program, running on the customer's computer, need the path of the .cpp file on the developer's machine? The C++ **compiler** needs that path, the linker needs the path of the object files, and after that you don't need those paths anymore. – MSalters Sep 14 '16 at 08:27
  • 1
    "I need path where my .cpp file reside". What for? What should happen if you buildvthe orogram and then copy the executable over to another machine? Do you still need a path on your development computer? – n. m. could be an AI Sep 14 '16 at 08:46
  • n.m. ya you are right . i will not need path of developer machine after moving executable. I was need so i misunderstood concept wrongly. – kandarp Sep 14 '16 at 12:46

3 Answers3

3

You're doing nothing wrong.

getcwd() gives you the current directory of the executing process.

When you instruct whatever tool you're using to build your C++ code to run it, it simply runs the process from that directory.

There is nothing in the C++ library that tells the application the location of its source code.

If you need your application to know where its source code lives, you need to pass that either as an argument to main(), or put it into some configuration file, that your application reads, or any similar approach.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
1

What you want to do is use the __FILE__ macro, and then use basic tokenization to extract the directory name.

Your method does not work since during execution, the current directory is that of the binary, not of the compilation unit.

RomanK
  • 1,258
  • 7
  • 18
0

If you use cmake, add this to the CMakeLists.txt of the source code directory:

add_definitions(-DMY_SRC_DIR="${CMAKE_CURRENT_SOURCE_DIR}")

before your add_library() or add_executable(). Then, in you source code you can use MY_SRC_DIR as a macro definition:

std::string mySrcDir = MY_SRC_DIR;

Your IDE won't like it at first, until you rerun cmake, then it will resolve that macro.

Cosmo
  • 491
  • 7
  • 14