In this post, we use ARM are reference architecture for writing the assembly code but the basic way of accessing functions defined in assembly program from C should remain almost similar ( except instructions ) for other architectures. Q. Write a C program helloworld.c which would call a function “simpleAdd” defined in assembly code ?
Execution & Command Syntax
make a layout of C program as, $ vim helloworldsed “globl” to export from here so it can be called from C programgcc -g -c add_assemblyTechnical Implementation Details
First make a layout of C program as, $ vim helloworld.c #include <stdio.h> extern void simpleAdd(void); int main(int argc, char **argv) { simpleAdd(); printf("HelloWorld after addtion from assembly program"); return 0; } Here, we declared simpleAdd function to be written in assembly and called from inside main. Now, we will write the assembly code for this simpleAdd function inside add_assembly.S file as, $ vim add_assembly.S .globl simpleAdd .text .thumb .type simpleAdd,%function simpleAdd: .fnstart MOV R0, #1 MOV R1, #2 ADD R2, R1, R0 BX lr .fnend as you can see above, we defined a function label as “simpleAdd” and used “globl” to export from here so it can be called from C program. The mov and add instruction just defines and adds two number with final addition result in R2 register. Note the end of function with “BX lr” as this is required to return the execution back to C code since Link Register “LR” contains the return address. You can compile this C and Assembly code using ARM GCC compiler and link those objects to create final executable as, Compile assembly code, this creates add_assembly.o as output object file. $ arm-linux-gnueabihf-gcc -g -c add_assembly.S Compile helloworld.c program and create respective object file helloworld.o as, $ arm-linux-gnueabihf-gcc -g -c helloworld.c Now, link both object files add_assembly.o and helloworld.o to generate the executable as, $ arm-linux-gnueabihf-gcc -g -o helloworld helloworld.o add_assembly.o -static Notice: here we have used “-g” to add debug symbols to debug with GDB and its not necessary.
Gotchas and Common Issues
Permission Verification - confirm execution permissions and path variables before invoking system binaries.
Version Compatibility - check software version release notes for deprecated flags or syntax changes.
Log Monitoring - inspect system logs (
journalctlor/var/log) to troubleshoot execution failures.
Following these steps ensures clean configuration, proper security boundaries, and reliable execution for call assembly function from c code.
Comments and corrections