简体   繁体   中英

Can I write (x86) assembly language which will build with both GCC and MSVC?

I have a project which is entirely written in C. The same C files can be compiled using either GCC for Linux or MSVC for Windows. For performance reasons, I need to re-write some of the code as x86 assembly language.

Is it possible to write this assembly language as a source file which will build with both the GCC and MSVC toolchains? Alternatively, if I write an assembly source file for one toolchain, is there a tool to convert it to work with the other?

Or, am I stuck either maintaining two copies of the assembly source code, or using a third-party assembler such as NASM ?

I see two problems:

  • masm and gas have different syntax. gas can be configured to use Intel syntax with the .syntax intel,noprefix directive, but even then small differences remain (such as, different directives). A possible approach is to preprocess your assembly source with the C preprocessor, using macros for all directives that differ between the two. This also has the advantage of providing a unified comment syntax.

    However, just using a portable third party assembler like nasm is likely to be less of a hassle.

  • Linux and Windows have different calling conventions. A possible solution for x86-32 is to stick to a well-supported calling convention like stdcall . You can tell gcc what calling convention to use when calling a function using function attributes . For example, this would declare foo to use the stdcall calling convention:

     extern int foo(int x, int y) __attribute__((stdcall)); 

    You can do the same thing in MSVC with __declspec , solving this issue.

    On x86-64, a similar solution is likely possible, but I'm not exactly sure what attributes you have to set.

    You can of course also use the same cpp-approach as for the first problem to generate slightly different function prologues and epilogues depending on what calling convention you need. However, this might be less maintainable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM