0

I have a file

1) File myStubs.cpp

 #include <stdlib.h>
 #include <new>

 void*     qMalloc(size_t sz)             {return malloc(sz);}
 void      qFree(void* ptr)               {free(ptr);}
 void*     qRealloc(void* ptr, size_t sz) {return realloc(ptr, sz);}

I make a static library from this file

1) g++ -fPIC -c myStubs.cpp -o lib_mylib.o
2) ar rcs libMyLib.a lib_mylib.o

In Qt Core we have file qglobal.cpp

2 ) File is qt-x11-opensource-src-4.3.3/src/corelib/global/qglobal.cpp and same functions as above in this file are

 /*
 These functions make it possible to use standard C++ functions with
 a similar name from Qt header files (especially template classes).
*/
Q_CORE_EXPORT void *qMalloc(size_t size);
Q_CORE_EXPORT void qFree(void *ptr);
Q_CORE_EXPORT void *qRealloc(void *ptr, size_t size);

When I link the static library libMyLib.a and static library of QtCore (libQtCore.a) and QtGui (libQtGui.a) . I am getting following build error

lib/libQtCore.a(qglobal.o): In function `qMalloc(unsigned long)':
qglobal.cpp:(.text+0x170): multiple definition of `qMalloc(unsigned long)'
libMyLib.a(myStubs.o):myStubs.cpp:(.text+0x0): first defined here

Questions

1) If I remove qMalloc , qFree and qRealloc from file myStubs.cpp, I do not get the build error , Is this correct way of solving this problem

Looking forward for the feedback

TechEnthusiast
  • 273
  • 4
  • 18

1 Answers1

0

If it is the correct way to solve the problem depends on why you have those stubs in the first place. You don't explain that.

But static linking works by looking in each library in turn to see if there is any member that would resolve any symbols not yet resolved at that point. So your myStubs.o resolves one or more symbols unresolved at that point. That file gets included, and all symbols in that file become part of the executable you build.

When the linker later on sees qglobal.o it contains some additional symbols that are not yet resolved. Then it tries to include that file too in the executable.

But then two definitions of the symbols become part of the executable, and that isn't legal. Thus the error message.

If you want to stub out some symbols, and want to do static linking, you need to stub out all symbols in qglobal.o that are used anywhere in the program.

Göran Uddeborg
  • 351
  • 3
  • 10