Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding leading underscores to assembly symbols with GCC on Win32?
    primarykey
    data
    text
    <p>I have a piece of C code that calls a function defined in assembly. By way of example, let's say foo.c contains:</p> <pre><code>int bar(int x); /* returns 2x */ int main(int argc, char *argv[]) { return bar(7); } </code></pre> <p>And bar.s contains the implementation of bar() in x86 assembly:</p> <pre><code>.global bar bar: movl 4(%esp), %eax addl %eax, %eax ret </code></pre> <p>On Linux I can easily compile and link these sources with GCC as follows:</p> <pre><code>% gcc -o test foo.c bar.s % ./test; echo $? 14 </code></pre> <p>On Windows with MinGW this fails with an error of "undefined reference to `bar'". It turns out the cause for this is that on Windows all identifiers of functions with C calling convention are prefixed with an underscore, but since "bar" is defined in assembly, it doesn't get this prefix and linking fails. (So the error message is actually complaining about missing the symbol _bar, not bar.)</p> <p>To summarize:</p> <pre><code>% gcc -c foo.c bar.s % nm foo.o bar.o foo.o: 00000000 b .bss 00000000 d .data 00000000 t .text U ___main U _bar 00000000 T _main bar.o: 00000000 b .bss 00000000 d .data 00000000 t .text 00000000 T bar </code></pre> <p>The question now is: how can I resolve this nicely? If I were writing for Windows only, I could just add the underscore to the identifier in bar.s, but then the code breaks on Linux. I have looked at gcc's <code>-fleading-underscore</code> and <code>-fno-leading-underscore</code> options but neither appears to do anything (at least on Windows).</p> <p>The only alternative I see now is passing the assembly file through the C preprocessor and redefining all the declared symbols manually if WIN32 is defined, but that's not very pretty either.</p> <p>Does anyone have a clean solution for this? Perhaps a compiler option I oversaw? Maybe the GNU assembler supports a way to specific that this particular symbol refers to a function using C calling convention and should be mangled as such? Any other ideas?</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.
 

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