這是我在彙編中定義函數的方法,這不需要單獨的彙編程序文件,也不需要轉義每一個換行符。您可以將程序集文件的內容複製到字符串文字中。 注意:raw multiline string literal是一個C++ 11功能(您也標記爲C++)。如果要編譯單個文件中的所有內容,這非常有用。
extern"C" int rand_byte(void);
asm (R"(
.globl rand_byte
rand_byte:
call rand
and eax, 255
ret
)");
您只能使用一個基本的彙編語句沒有在全球範圍內的其他參數。 使用GCC或Clang和手臂處理器時,您可以使用[[gnu::naked]]
/__attribute__((naked))
。
[[gnu::naked]]
int rand_byte(void) {
asm volatile (R"(
push {lr}
bl rand
and r0, #255
pop {pc}
)");
};
第一種方式總是允許定義裸露功能。 這也有助於製作更多可移植的代碼。
extern"C" int _cdecl rand_byte(void);
#if defined __x86__
// NOTE: the names are decorated with a '_' on windows 32-bit
// You can use extern"C" int _cdecl rand_byte() asm("rand_byte");
// to make the asm symbol name always be rand_byte, without an _
asm volatile (R"(
.globl _rand_byte
_rand_byte:
call rand
and eax, 255
ret
)");
#elif defined __x86_64__
asm volatile (R"(
.globl rand_byte
rand_byte:
call rand
and rax, 255 # eax works here, too. x86-32 and -64 could share the same source.
ret
)");
#elif defined __arm__
asm (R"(
.global rand_byte
rand_byte:
push {lr}
bl rand
and r0, #255
pop {pc}
)");
#else
#error There is no code for your platform yet...
#endif
試着讓這個更具體 - 它的含義相當寬泛和模糊 - 否則它可能會被視爲「不是真正的問題」。也請回顧一下早先關於使用'gcc -S ...'生成asm模板等問題的建議。 –
gcc以同樣的方式擁有'__attribute __((naked))',但不適用於x86 :( –