1

If I do this below:

#include <stdio.h>

int main()
{

 printf ("%s\n",__FILE__);
 return 0;

}

>gcc cfilename.c
>./a.out
>cfilename.c
>pwd
>/home/tek/cpp
> gcc -v
> gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5)

only file name is printed, I think it should print it with complete path, google search tells me people asking help to get only file name?

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
user3317205
  • 11
  • 1
  • 2

1 Answers1

4

The ISO C standard (currently C11) has this to say about the content of the __FILE__ predefined macro:

__FILE__: The presumed name of the current source file (a character string literal).

And that's about it. There is no mandate on the format of the content so I suspect a implementation could probably get away with setting it to "some file I found in the /src tree" and still claim conformance.

So it's basically up to the implementation as to what it puts in there. You'll need to investigate specific implementations to see how they handle it. The gcc compiler, for example, uses the file exactly as you specified on the command line so, if you want the full path, it's the command line you'll have to change, something like:

gcc -o myexec $(pwd)/myexec.c

It's interesting to note that gcc seems to do the opposite for included files. When you use:

#include "myheader.h"

the __FILE__ macro is set to the full expansion of the header file.


If you have an implementation that doesn't set __FILE__ in the manner you need, there's nothing stopping you from creating your own with something like:

dodgycc -o myexec -DMY_FILE_NAME=$(pwd)/myexec.c myexec.c

(where the -D option of the dodgycc compiler defines a preprocessor token to be what you need).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • Source files are always found at the given path, relative to the CWD, no ambiguity. A header with a given name, or include-name token with multiple components, is found relative to any of the configured header search paths. If `__FILE__` didn't mention the search path the header was found at, then multiple files could provide the same value for `__FILE__`, which would be ambiguous. – Potatoswatter Mar 07 '14 at 07:55
  • … Also it bears mentioning that if you want `__FILE__` to produce a particular result, the `#line` directive is the way to go. Anyway, +1. – Potatoswatter Mar 07 '14 at 07:56
  • Since v.8 `gcc` has options `-fmacro-prefix-map`, `-ffile-prefix-map` to modify how `__FILE__` expands. See https://stackoverflow.com/questions/8487986/file-macro-shows-full-path – ddbug Oct 25 '22 at 20:55