2 works

Cross-Platform Inline x86/x64 Assembly Macros


dashboard+ Project

Posted by @zcanann #c++

// Define macros for inlining x86 assembly in a compiler-independent way
#ifdef _MSC_VER
	#define ASM1(asm_literal) \
		__asm asm_literal
	#define ASM2(asm_literal1, asm_literal2) \
		__asm asm_literal1, asm_literal2
	#define ASM3(asm_literal1, asm_literal2, asm_literal3) \
		__asm asm_literal1, asm_literal2, asm_literal3

	#define ASM_MOV_REG_VAR(register, variable) \
		ASM(mov register, variable)

	#define ASM_MOV_VAR_REG(variable, register) \
		ASM(mov variable, register)

#elif __GNUC__ || __clang__
	#define ASM1(asm_literal) \
		ASM_GCC(#asm_literal)
	#define ASM2(asm_literal1, asm_literal2) \
		ASM_GCC(#asm_literal1 ", " #asm_literal2)
	#define ASM3(asm_literal1, asm_literal2, asm_literal3) \
		ASM_GCC(#asm_literal1 ", " #asm_literal2 ", " #asm_literal3)
	
	#ifdef __x86_64__
		#define ASM_MOV_REG_VAR(register, variable) \
			__asm__ __volatile__("movq %0, %%" EXPAND_AND_QUOTE(register)  : /* no outputs */ : "m"(variable) : )

		#define ASM_MOV_VAR_REG(variable, register) \
			__asm__ __volatile__("movq %%" EXPAND_AND_QUOTE(register) ", %0"  : "=m"(variable) : /* no inputs */ : )
	#else
		#define ASM_MOV_REG_VAR(register, variable) \
			__asm__ __volatile__("mov %0, %%" EXPAND_AND_QUOTE(register)  : /* no outputs */ : "m"(variable) : )

		#define ASM_MOV_VAR_REG(variable, register) \
			__asm__ __volatile__("mov %%" EXPAND_AND_QUOTE(register) ", %0"  : "=m"(variable) : /* no inputs */ : )
	#endif

	#define ASM_GCC(asm_string) \
		__asm__ __volatile__(".intel_syntax noprefix;" asm_string ";.att_syntax prefix"); \
	
#endif
content_copyCopy to Clipboard

Works with G++/Clang/MSVC Example usage: int count = 0; int* countPtr = &count; ASM(push eax); ASM_MOV_REG_VAR(eax, countPtr); ASM(inc [eax]); ASM(pop eax);


>> Browse more code snippets

more_vert