Monday, December 28, 2009

Note on C/C++[2]

an interesting one with gcc on Mac OS X

Compiler: gcc version 4.0.1 (Apple Inc. build 5490)
using built-in specs.
Target: i686-apple-darwin9
Configured with: /var/tmp/gcc/gcc-5490~1/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9
Thread model: posix

Environment: Mac OS X 10.5, Macbook ( intel-based)

Files: main.c and main.cpp. The two files are 100 percent the same ( checked with diff ). Here is the content:

#include

main(int argc, char *argv[])
{
int tmp = 100;
int *ptmp = &tmp;
char *p = "Hello, world!";
char a[] = "Hello, world!";
char ab[10];
printf("%d\n",*ptmp);
printf("%x\n",ptmp);
printf("%x\n",a);
printf("%x\n",p);
printf("%x\n",&ab[9]);
}

Symptom:
In the terminal, type gcc main.c , then ./a.out, the result is
100
bffff874
bffff866
1fe8
bffff865
however if I try gcc main.cpp, I got a compile-time error such that
Undefined symbols:
"___gxx_personality_v0", referenced from:
___gxx_personality_v0$non_lazy_ptr in cc6nXMVm.o
ld: symbol(s) not found
collect2: ld returned 1 exit status

Gee, this is funny! The only difference between these two source files is the name suffix!
My first guess is the default linker. I bet for this compiler the default links are different for *.c and *.cpp files ( one is gcc and another is g++?). This is confirmed when I tried gcc main.cpp -c and it worked fine but gcc main.o -o failed. But anyway it's still interesting to me!