I am trying to call assembler function from C++ but facing linkage error. I am using Clang(Apple 11.0.0) on Mac OS and cmake. Here is my cmake file:
cmake_minimum_required(VERSION 3.13)
project(bitShiftAsm)
set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_CXX_STANDARD 17)
add_custom_command(
OUTPUT ${CMAKE_SOURCE_DIR}/func.o
WORKING_DIR ${CMAKE_SOURCE_DIR}
COMMAND nasm -f macho64 ../func.asm
)
SET(OBJS
${CMAKE_SOURCE_DIR}/func.o
)
add_executable(bitShiftAsm ${OBJS} main.cpp)
SET_SOURCE_FILES_PROPERTIES(
${OBJS}
PROPERTIES
EXTERNAL_OBJECT true
GENERATED true
)
Assembler file:
global _my_fn
_my_fn:
mov rax, rdi
add rax, 100
ret
C++ file:
#include <iostream>
extern "C" long my_fn(long in);
int main()
{
cout << "Result: " << my_fn(3) << endl;
}
Linkage error is:
nasm -f macho64 ../func.asm
c++ -g -isysroot
MacOSX10.15.sdk -mmacosx-version-min=10.14 -std=gnu++1z -o
CMakeFiles/bitShiftAsm.dir/main.cpp.o -c .../bitShiftAsm/main.cpp
[100%] Linking CXX executable bitShiftAsm
cmake -E cmake_link_script CMakeFiles/bitShiftAsm.dir/link.txt --verbose=1
c++ -g -isysroot
MacOSX10.15.sdk -mmacosx-version-min=10.14 -Wl,-search_paths_first -Wl,-
headerpad_max_install_names CMakeFiles/bitShiftAsm.dir/main.cpp.o ../func.o -
o bitShiftAsm
Undefined symbols for architecture x86_64:
"_my_fn", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture x86_64
I have separate command to compile asm file and generate .o file from it. Appreciate any help. Thanks in advance.