Udit Sanghi
Udit Sanghi

Reputation: 21

How to print the path to the place where program was compiled in c

I know we can print the path of the current working directory using something like getcwd() but if the program was compiled in one place and the executable was copied to some other place, it will give the result as the new directory.

How do we store the value of getcwd() or something during compilation itself?

Upvotes: 0

Views: 2139

Answers (4)

Jabberwocky
Jabberwocky

Reputation: 50775

Depending on your compiler this may work:

#include<stdio.h>

int main()
{
  printf("This file path: %s\n", __FILE__);
}

__FILE__ is a predefined string literal that contains the full path of the .c file at compilation time.

If you want just the directory, you need to can strip off the filename yourself by a some trivial string manipulations.

This works under Visual Studio 2017. I didn't test it with other platforms. Apparently on most other platforms __FILE__ just contains the filename without the path.

Upvotes: 0

IcedLance
IcedLance

Reputation: 426

If you use cmake in you build process, you can add add_definitions(-DSOME_DIR="${CMAKE_CURRENT_BINARY_DIR}") to a correct CMakeLists.txt file. That is equivalent to #define SOME_DIR "binaries_dir" in the code.

Alternatively you can use any other build automation tool to make sure compiler gets passed the correct -D (GNU) or /D (MSVC) flag to generate a correct definition (or pass it to compiler manually, which is no different from specifying it in the code).

Upvotes: 1

Mathieu
Mathieu

Reputation: 9629

You can do this using makefiles, in makefile, add a macro that retain the pwd result:

Makefile:

CFLAGS += -DCURRENT_DIR=\"$(shell pwd)\"

In c file, use this value:

#include <stdio.h>

int main(void)
{
    printf("file %s compiled from %s\n", __FILE__, CURRENT_DIR);
    return 0;
}    

Upvotes: 2

Sander De Dycker
Sander De Dycker

Reputation: 16243

You could pass it as a compile-time define :

#include <stdio.h>

int main(void) {
    printf("COMPILE_DIR=%s\n", COMPILE_DIR);
    return 0;
}

And then :

/dir1$ gcc -DCOMPILE_DIR=\"$(pwd)\" current.c -o current

Resulting in :

/dir1$ ./current 
COMPILE_DIR=/dir1
/dir1$ cd /dir2
/dir2$ cp /dir1/current ./
/dir2$ ./current
COMPILE_DIR=/dir1

Upvotes: 3

Related Questions