I recently noticed something odd when compiling the following C++ program:
int main() { return 0; }
using g++
on linux. Specifically, I compiled the program (located in /a/directory
) twice using the following two commands:
g++ -g -o main main.cc
andg++ -g -o /a/directory/main /a/directory/main.cc
.
For each program I entered gdb main
, typed break main
and ran the programs. I got the following results when gdb hit the break points:
- Breakpoint 1,
main ()
atmain.cc:1
and - Breakpoint 1,
main ()
at/a/directory/main.cc:1
.
Simply put, g++
embeds a reference to the source directory in the binary while compiling with debugging symbols. What is more, this directory is the (literal, not normalized) directory passed to the compiler (this is confirmed by examining the binaries using strings
).
Apparently, cmake
builds execute g++
in such a way that the directory is absolute, at least when building out-of-source. Conversely, I encountered one autotools
managed project in which the source directories are local ones.
There are actually valid reasons to avoid using the absolute build directory, so I would like to know the following:
Can I influence the source directory that is put into a library / executable using some compiler option? How can this be done for an entire project when using cmake (like setting directories relative to the project root)?
Secondly, I would like to know if there is a convention regarding the source directory on Linux. Ideally, it would be possible to install the sources and tools like gdb
would pick up the actual location by using something like a source $PATH
.