This is the mail archive of the
binutils@sourceware.org
mailing list for the binutils project.
Understanding multiple definitions in C program
- From: "linu cherian" <linuc dot decode at gmail dot com>
- To: binutils at sourceware dot org
- Date: Mon, 18 Jul 2016 09:00:37 +0530
- Subject: Understanding multiple definitions in C program
- Authentication-results: sourceware.org; auth=none
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