How to get path to source file?

Apr 18, 2012 at 4:23pm
I'm looking for a function that gives me the absolute file path of the file calling that function. For example if main.cpp calls this method, then the absolute path should end with "main.cpp"

I've done a bit of research and these functions are not what I'm looking for
GetCurrentDir()
GetCurrentDirectory()
Provides absolute path to working directory, which is my /project/ directory.

GetModuleFileName()
Provides the path to the .exe


Thanks in advance.
Apr 18, 2012 at 5:04pm
There is nothing in C++ for this. You are asking for reflective capabilities found only in higher level languages like Java and .net. C++ doesn't provide this feature.

The best you can do is log and use the macro __FILE__.

func.cpp:
1
2
3
4
5
6
#include "func.h"

void MyFunc()
{
    Log("This is code file " __FILE__);
}


main.cpp:
1
2
3
4
5
6
7
8
#include "func.h"

int main()
{
    Log("This is code file " __FILE__ " about to call function MyFunc()...");
    MyFunc();
    Log("main() finished.");
}


And you would have a Log() function that logs to a file or something else. Example:
1
2
3
4
5
//This logs to the console.
Log(const char * const message)
{
    std::cout << message << std::endl;
}


Output:
This is code file C:\MyProject\main.cpp about to call function MyFunc()...
This is code file C:'\MyProject\func.cpp
main() finished.
Apr 18, 2012 at 5:19pm
Awesome, thanks, this is what I was looking for.
Topic archived. No new replies allowed.