This is the mail archive of the binutils@sourceware.org mailing list for the binutils project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Understanding multiple definitions in C program


Why would you expect it to do so?  You wrote a program to override the library definition and use your own instead, the compiler and linker did what you asked for.

	paul

> On Jul 17, 2016, at 11:30 PM, linu cherian <linuc.decode@gmail.com> wrote:
> 
> Hi,
> 
> Recently observed that, gcc doesnt warns/give error when i had a
> private malloc definition in my C program, though it had dependency on
> the libc. 
> 
> main.c
> ----------
> #include <stdio.h>
> #include <stdlib.h>
> 
> 
> int main()
> {
> 
>  printf("Calling malloc\n");
> 
>  malloc(100);
> }
> 
> malloc.c
> -------------
> #include <stdio.h>
> #include <stdlib.h>
> 
> 
> void *malloc(size_t x)
> {
>  printf("hello my malloc %lu \n", x);
>  /* do nothing */
> }
> 
> Makefile
> -------------
> all: malloc
> 
> 
> libmalloc.so:libmalloc.o
>        gcc -shared  malloc.o -o libmalloc.so
> 
> libmalloc.o: malloc.c
>        gcc -fpic -c malloc.c
> 
> 
> 
> malloc: main.c libmalloc.so
>        gcc  malloc.c main.c -L. -lfoo -o malloc
> 
> 
> clean:
>        rm -f *.a *.o
> 
> 
> When i compiled and ran the above code, the output was,
> # export LD_LIBRARY_PATH=.
> #./malloc
> Calling malloc
> hello my malloc 100
> 
> #gcc --version
> gcc (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3
> Copyright (C) 2011 Free Software Foundation, Inc.
> This is free software; see the source for copying conditions.  There is NO
> warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
> 
> 
> 1. On what criteria, does the  malloc symbol get resolved, since we
>   have multiple  definitions, one in libmalloc and other libc. 
> 
> 2. Wont it be better if gcc reports multiple definitions as error, since
>    - allowing multiple definitions is error prone
>    - there is inconsistency on  how gcc handles multiple definitions
>      with regard to -static and without -static.
>      (ie. with -static gcc reports error for this)
> 
> 3. Could someone please help me understand why multiple definitions
>   are desired in dynamic linked case ? 
> 
> Appreciate your help.
> 
> Thanks.
> -- 
> Linu cherian


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]