c++ - How does the linker determine which function to link to? -
c++ - How does the linker determine which function to link to? -
the code below simplified version of problem seeing; external function testprint()
ended calling printf()
defined in test_xprintf.cpp
instead of standard printf()
.
(yes, code looks odd, meant represent problem, not makes sense itself.)
why did linker link printf()
defined in test_xprintf
? expected behaviour or tool dependent?
// // test_xprintf.cpp // #include <iostream> #include <stdio.h> #include <stdarg.h> #include "test_dbgprintf.h" /** * * there 3 files in total: * - test_xprintf.cpp * - test_dbgprintf.h * - test_dbgprintf.cpp * * create static c lib test_dbgprintf.c , link test_xprintf.cpp * * gcc -wall -g -c -o test_dbgprintf.o test_dbgprintf.c && * ar -rcs libtest_dbgprintf.a test_dbgprintf.o && * g++ -wall test_xprintf.cpp -l. -ltest_dbgprintf -i. */ extern "c" int printf(const char *format, ...) { va_list ap; va_start(ap, format); vprintf(format, ap); va_end(ap); homecoming -1; } int main() { // testprint() shell function calls printf. // if printf function above called, homecoming value -1. int ret = testprint(4); std::cout << "ret value " << ret << std::endl; homecoming ret; }
class="lang-c prettyprint-override">// // test_dbgprintf.h // #ifndef test_dbgprintf_h #define test_dbgprintf_h #if defined (__cplusplus) extern "c" { #endif int testprint(int num); #if defined (__cplusplus) } #endif #endif
class="lang-c prettyprint-override">// // test_dbgprintf.c // #include <stdio.h> int testprint(int num) { // right should calling std printf linked printf in test_printf.cpp instead. homecoming printf("this called testprint %d\n", num); }
it known behavior gnu linker. when resolving symbol, observe multiple definitions between .o's; resort libraries if no definition found in .o's; , stop search after first match.
that's default behavior. may override --whole-archive
, though may bloat resulting module.
c++ c linker
Comments
Post a Comment