-4

How could I get the adress of a c++ source's parent directory (and all directories of higher level) - from within the code itself? I.e. program created from the source can access said directories without me specifying them.

Ylfaue
  • 131
  • 1
  • 7
  • I should add - I don't use any IDE and compile on the command line. – Ylfaue Apr 18 '15 at 23:12
  • 2
    May I ask for your use case for that? – Dimitri Schachmann Apr 18 '15 at 23:15
  • @DimitriSchachmann That's a very good question, because relying on a source directories' resource at runtime usually is a bad idea. – πάντα ῥεῖ Apr 18 '15 at 23:19
  • possible duplicate of [How to get current source path in C++ - Linux](http://stackoverflow.com/questions/20394183/how-to-get-current-source-path-in-c-linux) – Irrational Person Apr 18 '15 at 23:29
  • 1
    The location of the source code a program was compiled from generally isn't very useful information. This sounds like an XY problem. Can you clarify how you plan to use this information? What would happen if your program was run on a different machine? – Retired Ninja Apr 18 '15 at 23:47

2 Answers2

4

You can use the __FILE__ macro to get the path of the source file. Then by applying string manipulation techniques you can simply get the parent directory.

More info here.

1

Some compilers support the __FILE__ macro, you can use to get a character literal with the full path of your source file.

You can extract the parent directory names from this literal if it's available.


But what's your use case for doing so actually?

I have some doubts about your deployment strategies, possibly in question.

If you rely on source directory structures, to e.g. load further resource files, that's not portable for potential target environments, that only have your executable artifacts installed. You may reconsider your deployment and configuration strategies.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • Is the `__FILE__` macro optional to support by compilers? I thought it was in the C and C++ standards. It's been in all the compilers I have used for the last 20 years. – Thomas Matthews Apr 19 '15 at 02:40