C++ inline assembly

Created By: chatGPT

C++ supports inline assembly, allowing you to write assembly code directly in your C++ programs. This can be useful for performance-critical sections of code or to utilize specific CPU instructions that are not directly accessible from C++. The syntax can vary depending on the compiler being used. Here, we'll focus on GCC and MSVC compilers as examples.
int main() {
    int a = 5;
    int b = 10;
    int sum;

    __asm__ (
        "mov %1, %%eax;"
        "mov %2, %%ebx;"
        "add %%ebx, %%eax;"
        "mov %%eax, %0;"
        : "=r" (sum)
        : "r" (a), "r" (b)
        : "%eax", "%ebx"
    );

    printf("Sum: %d\n", sum);
    return 0;
}

In the above example for GCC, we define three operands with the syntax:

  • %0 for output,
  • %1 and %2 for inputs. The ": "=r" (sum) indicates that sum is an output variable, and ": "r" (a), "r" (b) indicates that a and b are inputs. The clobbered registers are specified to inform the compiler that these registers are modified during the assembly code execution.
int main() {
    int a = 5;
    int b = 10;
    int sum;

    __asm {
        mov eax, a;   // Load a into eax
        mov ebx, b;   // Load b into ebx
        add eax, ebx; // eax = eax + ebx
        mov sum, eax; // Store result in sum
    }

    printf("Sum: %d\n", sum);
    return 0;
}
For MSVC, the inline assembly is placed in a different block syntax, meaning you use __asm. It doesn’t utilize the operand syntax that we saw in GCC. Instead, you just write the assembly instructions like you normally would. Note that not all C++ compilers support inline assembly, so it’s essential to refer to your specific compiler documentation.
#include <stdio.h>

int main() {
    int a = 5;
    int b = 10;
    int sum;

    __asm {
        mov eax, a;
        mov ebx, b;
        add eax, ebx;
        mov sum, eax;
    }

    printf("Sum: %d\n", sum);
    return 0;
}
Important Note: When using inline assembly, be cautious as it can make your code less portable and harder to maintain. Moreover, when optimizing, compilers may disregard inline assembly, so profiling is always recommended to ensure performance benefits. Additionally, ensure that memory management and data types are compatible between C++ and assembly.
// Inline assembly can contain low-level hardware interactions. Use with caution.
Introduction And SetupVariablesData TypesIntFloatDoubleCharBoolStringVoidConstantsOperatorsArithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsTernary OperatorControl FlowIf StatementElse StatementElse If StatementSwitch StatementFor LoopWhile LoopDo While LoopBreak StatementContinue StatementGoto StatementFunctionsFunction DeclarationFunction DefinitionFunction OverloadingInline FunctionsDefault ArgumentsRecursionPass By ValuePass By ReferenceData StructuresArraysMultidimensional ArraysStructsEnumsUnionsClassesObjectsMember FunctionsConstructorsDestructorsAccess SpecifiersPublicPrivateProtectedInheritancePolymorphismFunction OverridingVirtual FunctionsPure Virtual FunctionsOperator OverloadingTemplatesNamespaceCommentsSingle Line CommentsMulti Line CommentsSyntaxSemicolonCurly BracesParenthesesEvent HandlingCinCoutError HandlingTry BlockCatch BlockThrow StatementException HandlingPreprocessor DirectivesInclude GuardsMacro DefinitionsInline AssemblyStatic KeywordsExtern KeywordsConst KeywordsVolatile KeywordsFriend FunctionStatic MemberThis PointerDynamic Memory AllocationNew OperatorDelete Operator