0

I have the following assembler code in the at&t style:

# asmFunc.asm 

.global asmFunc

.section .text

asmFunc:
pushl %ebp
movl %esp, %ebp
addl $8,%ebp
movl %ebp, %eax
addl $4,%ebp
movl %ebp, %ebx
addl %eax,%ebx
movl %ebp, %esp
popl %ebp
ret

Then, I have a cpp file as follows:

// main.cpp
#include <iostream>

extern "C" int asmFunc(int a, int b);

int main() {
  int a,b;

  std::cout << "Type in 1st num: \n" << std::endl;
  std::cin >> a;
  std::cout << "Type in 2nd num: \n" << std::endl;
  std::cin >> b;
  std::cout << "Assembly function asmFunc(" << a << ", " << b << ") is" << asmFunc(a,b) << std::endl;

  return 0;
}

I compile the assembly code with "as asmFunc.asm -o asmFunc.o" which gives no problems. The cpp is compiled using "g++ -c main.cpp -o main.o". When I try to link the files though using "g++ main.o asnFunc.o -o start", I get the following linker error:

(.text+0xb5): undefined reference to `asmFunc'
collect2: error: ld returned 1 exit status

Why is this? I am using CygWin 32-bit for compiling and linking the sources.

Paul R
  • 208,748
  • 37
  • 389
  • 560
NeoSer
  • 527
  • 3
  • 16
  • I couldn't reproduce the error with gcc-Version 4.6.3 on ubuntu. Links well but gives memory error after entering the two numbers. asmFunc is correctly linked in `start` file. – zx485 Jan 17 '16 at 09:23
  • I have not tried this on Ubuntu. It can a problem with CygWin, can't it? – NeoSer Jan 17 '16 at 09:39
  • 1
    Suspect your function needs to be `_asmFunc`. [It's also incorrect, you want `4(%ebp)` and `8(%ebp)` instead of adding 4/8 to `%ebp` [which you then do not reverse, so will also mess up `%esp` on the way back out, and return to somewhere other than `main`] – Mats Petersson Jan 17 '16 at 09:49
  • Thanx for the tips. Now it works. I changed the global name, but forgot to change the definition name. Indeed, there has to be an underscore. – NeoSer Jan 17 '16 at 10:10
  • An alternative solution is described here, http://stackoverflow.com/questions/1034852/adding-leading-underscores-to-assembly-symbols-with-gcc-on-win32 – J.J. Hakala Jan 17 '16 at 11:40

0 Answers0