Versions used in this test:
Reading specs from /usr/lib/gcc/i686-pc-linux-gnu/3.4.6/specs
Configured with: /var/tmp/portage/gcc-3.4.6-r1/work/gcc-3.4.6/configure --prefix=/usr --bindir=/usr/i686-pc-linux-gnu/gcc-bin/3.4.6 --includedir=/usr/lib/gcc/i686-pc-linux-gnu/3.4.6/include --datadir=/usr/share/gcc-data/i686-pc-linux-gnu/3.4.6 --mandir=/usr/share/gcc-data/i686-pc-linux-gnu/3.4.6/man --infodir=/usr/share/gcc-data/i686-pc-linux-gnu/3.4.6/info --with-gxx-include-dir=/usr/lib/gcc/i686-pc-linux-gnu/3.4.6/include/g++-v3 --host=i686-pc-linux-gnu --build=i686-pc-linux-gnu --disable-altivec --enable-nls --without-included-gettext --with-system-zlib --disable-checking --disable-werror --disable-libunwind-exceptions --disable-multilib --disable-libgcj --enable-languages=c,c++,f77 --enable-shared --enable-threads=posix --enable-__cxa_atexit --enable-clocale=gnu
Thread model: posix
gcc version 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)
GNU ld version 2.16.1
The problem
consider given 2 files named test1.cpp and test2.cpp:
test1.cpp
#include <stdio.h>
int main(int argc, char *argv[]) {
printf("hello world\n");
return 0;
}
test2.cpp
int printf;
compiling with the command g++ -o test test1.cpp and running gives:
$ ./test
hello world
$
thats what is expected.
compiling g++ -o test test1.cpp test2.cpp and running gives:
$ ./test
Segmentation fault
running it in gdb gives:
$ gdb ./test
GNU gdb 6.4
Copyright 2005 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public...
welcome to change it and/or distribute copies of it under ...
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" ...
This GDB was configured as "i686-pc-linux-gnu"...Using host ...
(gdb) r
Starting program: /home/sash/tmp/test
Program received signal SIGSEGV, Segmentation fault.
0x080496a4 in printf ()
(gdb) bt
#0 0x080496a4 in printf ()
#1 0x0804845c in main ()
The Question
So what is going wrong, does the compiler mess up the printf() glibc call and the int var or is the the linker?
Is this behaviour wanted?
now imagine what happens if the variable is not called printf, but something like shutdown (as a global shutdown flag)
and some third party library uses shutdown() internally.
the gdb backtraces are either completely borked or misleading.
just as a note, declaring the variable in the same file as the usage is not working, g++ complains.