3

I recently discovered that when using the __FILE__ predefined macro in MSVC (specifically 2013) that by default it will print relative paths for source files and absolute paths for header files.

As an example I have a VS project containing the following:

Solution
    Project
        Headers
            foo.h
        Sources
            main.cpp

Both main.cpp and foo.h are in the same directory on disk.

main.cpp:

#include <iostream>
#include <string>

#include "foo.h"

int main(int, char*[])
{
    std::cout << __FILE__ << std::endl;
    foo::bar();

    std::cout << "Press enter to exit";
    std::string str;
    std::getline(std::cin, str);

    return 0;
}

foo.h:

#ifndef FOO_H
#define FOO_H

#include <iosfwd>

class foo
{
public:
    static void bar()
    {
        std::cout << __FILE__ << std::endl;
    }
};

#endif

When I run the application (in release mode, with the default settings - compiling with /Zi and /FC is not defined) then the output is:

main.cpp
c:\users\<user>\documents\dev\solution\project\foo.h
Press enter to exit

I know I could probably pass in a base path and strip it out at runtime but I was wondering whether there was any way to change this behavior at compile time? Obviously defining /FC produces the opposite result and I cannot see anything else in the MSVC manual to control the display of header paths. I am thinking this might be a hardcoded behavior so that if the compiler is able to pick up two files called foo.h from different include paths that you can still distinguish between them or because it would be possible to have an include path unrelated to the base of the sources and displaying as relative would be messy.

tinman
  • 6,085
  • 1
  • 28
  • 38
  • 1
    When calling the compiler, is the include path (/I paramater) specified as absolute or as relative path? If absolute, does the behaviour change if you pass a relative path? – sb9 Jan 10 '17 at 12:43
  • 1
    Also take a look at http://stackoverflow.com/questions/8487986/file-macro-shows-full-path – sb9 Jan 10 '17 at 13:15
  • @sb9: Thanks for linking the other Q. the include path is not set by the IDE since the header is in the same path as the source. Building from the command line and trying to set the /I parameter to absolute or relative makes no difference - it always prints the absolute path. – tinman Jan 12 '17 at 15:58
  • Does this answer your question? [\_\_FILE\_\_ macro shows full path](https://stackoverflow.com/questions/8487986/file-macro-shows-full-path) – phuclv Mar 30 '20 at 11:47

0 Answers0