Re: How does g++ link an objective file .o built by gcc?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Thu, 4 Jan 2024 at 18:48, Dingjun Chen
<Dingjun.Chen@xxxxxxxxxxxxxxxxxxx> wrote:
>
> HI, everyone,
>
> I have a question for you.
>
> I have multiple c++ files .cc (main program is C++) and one c file 'librtd-dm6620.c'. Of course I will use g++ to build the executable. For that 'librtd-dm6620.c' file I still want to build its .o file via gcc because there are some possibly fatal warnings if I use g++ to build this .c file. If this .c file is built with gcc, there is no any warning and it is perfect in compilation.

Then that means you are trying to compile C code using the C++
compiler. That might work sometimes, for some C code, but will often
not work. C and C++ are different languages.


>
> Finally, I want to build the executable by linking all .o files via g++.  The problem is that the .o file built by gcc is not really linked by g++.  All defined functions in 'librtd-dm6620.c' cannot be found by the g++ linker 'ld'.

That's because the C++ compiler uses "name mangling" when it compiles
functions, so that the symbol names in the .o are different when
compiled as C++.

For example, a function void f() { } will be compiled to a symbol
called "f" when compiled as C, but a symbol called "_Z1fv" when
compiled as C++.

You either need to compile all your C files as C++, so that the symbol
names are all consistent, or you need to tell the C++ compiler not to
mangle the names, like so:

#ifdef __cplusplus
extern "C" {
#endif
void f() { }
#ifdef __cplusplus
}
#endif

When this is compiled by a C++ compiler it will produce a symbol
called "f", just like when compiled by a C compiler.

The simplest answer is probably just to stop trying to compile C files
as C++ code. Either write C++, or write C, don't write C and then
compile as something different.




[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux