Reputation: 4391
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:
main ()
at main.cc:1
andmain ()
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
.
Upvotes: 1
Views: 899
Reputation: 738
CMake will always use absolute paths when compiling, reason is described here.
However, you can use the GCC option -fdebug-prefix-map
to change the debugging paths that are embedded in the binary. Its documentation is located here.
I tried this:
g++ -g -o `pwd`/main `pwd`/main.cc -fdebug-prefix-map=`pwd`=.
and the gdb output was: Breakpoint 1 at 0x1129: file ./main.cc, line 1.
For an entire project, passing -fdebug-prefix-map=<absolute path of source root>=<source root relative to build path>
would probably work. For example, if the sources are located under /a/directory/
and the build directory is /a/directory/build/
then you would pass -fdebug-prefix-map=/a/directory/=..
.
Edit: It was answered before: Make gcc put relative filenames in debug information
Upvotes: 1