Question:
How to use assembly function in C++ code?
Answer:
When using asm code from C++ code, you have to inform the build tools that these functions are in asm, so that it knows how to call them. When a asm source file is compiled, the function names are given an underscore prefix in the generated assembly. For example, "void foo(int a) {...}" becomes "_foo" in the generated assembly. This is the symbol used to call the function.
As C++ supports function overloading, simply adding an underscore would not differentiate between the variances of the same function. So, a suffix is added to the symbol name in assembly when a C++ source file is compiled. For example. "void foo(void)" becomes "_foo__Fv" ("__F" = function, "v" = void), while "void foo(unsigned char *a, int b)" would become "_func__FPUci" in the assembly file, where the "__FPUci" means the Function ("__F") takes a Pointer ("P") to an Unsigned char ("Uc"), and an integer ("i") as it's parameters: "__FPUci".
This is true not only when you build the source that contains the function definition, but also when you call the function from your code. Where this causes problems, is if you call "foo(void)" from your C++ source, but the function exists in a asm source file, the generated assembly will call "_foo_Fv", but the linker will not be able to resolve that reference, as compiling the C source file would only produce a symbol "_foo".
You can let the Compiler know how to resolve these references using the "extern" qualifier. For example, if you have a function named "asm_func()" in a asm source file, simply add the prototype to your C++ source code (or a header file included by the C++ source) as follows:
extern "asm" void asm_func(void);
This tells the C++ Compiler that "asm_func ()" is a asm function, and will generate references to this function in the generated assembly.
Also please note that, no need to add dot suffix in function definition of " asm_func()”, while using extern qualifier.