Note that there are some explanatory texts on larger screens.

plurals
  1. PO__attribute__((weak)) and LD_PRELOAD
    primarykey
    data
    text
    <p>I want a code to be able to run an application <em>with</em> a certain self-written library and <em>without</em> it. So I use the <code>__attribute__ ((weak))</code> and preload the library if needed. I need to be able to do that without recompiling. Everything works fine if I link the library statically, though.</p> <p>Furthermore the library is written in C++ while the applications using it can be C++ or C.</p> <p>I boils down to this:</p> <p>library header <code>test_lib.h</code>:</p> <pre><code>#ifdef __cplusplus extern "C" #endif void test_func() __attribute__ ((weak)); </code></pre> <p>library implementation <code>test_lib.cpp</code>:</p> <pre><code>#include "test_lib.h" #include &lt;iostream&gt; extern "C" void test_func() { std::cout &lt;&lt; "in test_func\n"; } </code></pre> <p>the C test <code>test_main.c</code>:</p> <pre><code>#include &lt;stdio.h&gt; #include "test_lib.h" int main(void) { if (test_func){ printf("+\n"); } else{ printf("-\n"); } return 0; } </code></pre> <p>the C++ test <code>test_main_cpp.cpp</code>:</p> <pre><code>#include &lt;iostream&gt; #include "test_lib.h" int main(void) { if (test_func){ std::cout &lt;&lt; "+\n"; } else{ std::cout &lt;&lt; "-\n"; } return 0; } </code></pre> <p>the compile and run script for your convenience:</p> <pre><code>#!/bin/bash g++ -shared -fPIC test_lib.cpp -o libtest.so gcc test_main.c -o test_c g++ test_main_cpp.cpp -o test_cpp # output should be "-" ./test_c ./test_cpp # output should be "+" LD_PRELOAD=libtest.so ./test_c LD_PRELOAD=libtest.so ./test_cpp </code></pre> <p>The expected output is:</p> <pre><code>- - + + </code></pre> <p>What I get is:</p> <pre><code>- - - - </code></pre> <p>and finally a little extra information:</p> <pre><code>$ uname -a Linux bermuda-iii 3.8.6-1-ARCH #1 SMP PREEMPT Sat Apr 6 07:27:01 CEST 2013 x86_64 GNU/Linux $ gcc --version gcc (GCC) 4.8.0 $ nm libtest.so | grep -i func 0000000000000858 W test_func $ nm test_c | grep -i func w test_func $ nm test_cpp | grep -i func w test_func </code></pre> <p>So: (de)mangling seems to work fine, the symbol <code>test_func</code> is known to the executables. But the `LD_PRELOAD´ doesn't seem to work. </p> <p>What am I missing?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload