Wollan
Wollan

Reputation: 939

Linking C function lib to x86 assembly program in modern 64bit Linux

I'm going through a book focusing on x86 programming (Professional Assembly Language, WROX 2005). I had some problems last night and I was hoping to sort this out before returning home today so I can get a running-start and continue the text. My machine runs x64 Ubuntu (11.04 if I'm not mistaken) so the text focusing on 32bit x86 is slightly 'outdated' (I have to add --32 when assembling etc).

I am trying to dynamically link C-library functions with my assembly program but I am unsuccesfull (below commands are from memory).

ld -dynamic-linking /lib/ld-linux.so.2 -o complex -lc complex.o -m elf_i386

Running the above command in Linux gives me the message that it can't understand -lc. Okay, so I removed it.

ld -dynamic-linking /lib/ld-linux.so.2 -o complex complex.o -m elf_i386

I then get the notification that 'printf' is not recognised. The hopes was for the dynamic linker to link to the library but it does not seem to do so. Going to \lib\ I could not locate ld-linux.so.2 (strangely it didn't give me an error on this) but I did locate ld-linux-86-64.so.2. My code is 32bit but I thought what the heck, let's try this:

ld -dynamic-linking /lib/ld-linux-86-64.so.2 -o complex complex.o -m elf_i386

Still it gave the same error that 'call printf' was not recognized.

Need help dynamically linking C library functions with my 32bit Assembly program using 64bit Linux and standard GNU tools.

Upvotes: 1

Views: 3458

Answers (3)

GB Zheng
GB Zheng

Reputation: 1

Try the following order please(suppose your code fil is try.s):

as  --32 -g -o try.o   try.s
ld -m elf_i386  -dynamic-linker /lib/ld-linux.so.2 -lc  -o try try.o

For x86-64 format executable file:

as   -g -o try.o   try.s
ld  -dynamic-linker  /lib64/ld-linux-x86-64.so.2 -lc  -o try try.o

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

Sounds like you need to install the 32-bit C-runtime. Under Fedora this is:

yum install glibc-devel.i686

But I don't know the name of the equivalent Ubunutu package; perhaps:

apt-get install libc6-dev-i386

Upvotes: 6

zwol
zwol

Reputation: 140569

It is almost always a bad idea to try to construct a ld command line yourself. Let GCC do it for you; it automatically handles all sorts of subtleties that you don't want to have to worry about. For a 32-bit program, you do need one special command line switch, -m32:

gcc -m32 -o complex complex.o

If you have more .o files, just stack them up at the end. If you need to link against any system libraries other than libc, put appropriate -lwhatever options after all the object files.

trojanfoe is also correct; the 32-bit toolchain is an optional component. But you need more than just the 32-bit C library. Try this first:

apt-get install gcc-multilib

it should pull in most of what you need.

Upvotes: 3

Related Questions