Warm tip: This article is reproduced from stackoverflow.com, please click
assembly c c++ inline-assembly

In what cases would I want to use inline assembly code in C/C++ code

发布于 2020-04-11 22:10:50

I just read that assembly code can be included directly in C/C++ programs, like,

__asm statement
__asm {
statement-1
statement-2
...
statement-n
}

I'm just wondering in what cases would it be useful to include assembly code in C/C++.

Questioner
pasha
Viewed
63
Simon Doppler 2020-02-02 17:08

The most significant place (and probably only one where it makes sense) where assembly use in C/C++ is used is in embedded systems development, where it is the only way to access some peripherals or where it is required to do so because we need this exact order of instructions no matter what the compilation flags are. This last case is most often seen in bootloaders or critical OS parts like the context switch.

The example that comes to mind is accessing the special registers in a MicroBlaze processor: even Xilinx recommends accessing those registers using assembly (there is also no other way that I know of) because there is no other way.

By embedding it in C, it would be used like this:

unsigned long get_msr(void) {
    unsigned long msr; 
    asm ("mfs %0, rmsr" : "=d" (msr)); // note: this is a gnu extention
    return msr;
}

Another example is the implementation for a context switch provided by ARM also uses assembly (although not embedded in C code in this case).