CMake provides flexibility to integrate various build tools. One option is NASM (Netwide Assembler), a widely-used assembler for the x86 and x86-64 computer architectures. Combining CMake with NASM allows assembly routines to be seamlessly included in C or C++ projects, which can be particularly useful for performance-critical functions. This tutorial shows how to use NASM with CMake.
Let's say we have a simple example which calls an assembly function from C++ which adds two integers and returns the result. The main.cpp file declares the external function and prints the sum to the terminal:
main.cpp
#include <iostream>
extern "C" int add(int a, int b);
int main() {
std::cout << add(2, 3) << std::endl;
return 0;
}
The add function is implemented in assembly using the calling convention specific to each platform. For Linux, the assembly code looks like this:
add_linux.asm
global add
section .text
add:
mov eax, edi
add eax, esi
ret
For Windows, the assembly code uses a slightly different calling convention:
add_windows.asm
global add
section .text
add:
mov eax, ecx
add eax, edx
ret
Finally, the CMakeLists.txt ties everything together:
CMakeLists.txt
cmake_minimum_required(VERSION 4.0)
project(myapp CXX ASM_NASM)
set(CMAKE_CXX_STANDARD 17)
if (WIN32)
set(PROJECT_SOURCES_ASM add_windows.asm)
else ()
set(PROJECT_SOURCES_ASM add_linux.asm)
endif ()
add_executable(${PROJECT_NAME} main.cpp ${PROJECT_SOURCES_ASM})
Here, NASM is enabled by specifying ASM_NASM in the project command. The if statement selects the correct assembly file depending on the platform, and add_executable combines both C++ and assembly sources into a single executable.
With this setup, CMake handles NASM compilation automatically. The result is a fully functional program where C++ and assembly coexist.
Leave a Comment
Cancel reply