[ACCEPTED]-How do I compile assembly routines for use with a C program (GNU assembler)?-compilation

Accepted answer
Score: 17

Based on the files in your question, I managed 22 to compile it. I've changed both the file 21 names and the file contents.

asm_const.h 20 :

#define ASM_CONST_1    0x80
#define ASM_CONST_2    0xaf

asm_functions.h :

#include "asm_const.h"
unsigned char asm_foo( int, int, int );

asm_functions.S (the trailing 19 S must be capital! #include needs it) :

#include "asm_const.h"
.section .text
.globl asm_foo
.type asm_foo, @function
  mov $ASM_CONST_1, %eax
  /* asm code with proper stack manipulation for C calling conventions */

test_asm.c 18 :

#include "asm_functions.h"
int main() {
  return asm_foo( 1, 2, 3);

Please note that you need the the assembly 17 file extension .S with capital S. With .s, the 16 .s file wouldn't be run through the preprocessor, thus 15 #include wouldn't work, and you wouldn't 14 be able to use ASM_CONST_1 in the .s file.

Compile 13 with a single command:

gcc -o test_asm asm_functions.S test_asm.c

Or, as an alternative, compile 12 with multiple commands, creating .o files:

gcc -c asm_functions.S
gcc -c test_asm.c
gcc -o test_asm asm_functions.o test_asm.o

The 11 single-command gcc takes care of compiling 10 the .S file using gas, the .c file with 9 GCC's C compiler, and linking the resulting 8 temporary .o files together using ld. gcc 7 runs all those commands with the appropriate 6 flags by default.

On some systems (but not 5 on Linux with the default GCC installation) you 4 have to prepend an underscore to the names 3 of exported functions in the .S file (but 2 not in the .c or .h files). So all instances 1 of asm_foo would become _asm_foo only in the .S file.

Score: 0

Have you considered using inline assembly? It would be much easier 6 than using an assembler file.

Edit: Also, the 5 reason you are getting linker errors is 4 probably because the C compiler adds a leading 3 underscore on identifiers for the actual 2 symbols. Try adding an underscore in your 1 assembly file.

More Related questions