10

I am trying to follow the tutorials in this link.

When I get down to the part where I start making a test.c file, I try to run the first compilation line.

gcc -c -g -Os -march=i686 -ffreestanding -Wall -Werror test.c -o test.o

Here is the contents of test.c

__asm__(".code16\n");
__asm__("jmpl $0x0000, $main\n");

void main() {
}

When I call the first compilation line, it shows me this error.

test.c:1:0: error: CPU you selected does not support x86-64 instruction set
 __asm__(".code16\n");
 ^

Can anyone tell me why this is happening? And if possible, how to fix it?

I am running Ubuntu Desktop x64, thank you in advance for your help.

EDIT:

I have changed the first compilation line to:

gcc -c -g -Os -m32 -ffreestanding -Wall -Werror test.c -o test.o

And it seems to work fine. However, there are two more lines that are giving me trouble.

ld -static -Ttest.ld -nostdlib --nmagic -o test.elf test.o

and

objcopy -O binary test.elf test.bin

The first one throws me the error of.

ld: i386 architecture of input file `test.o' is incompatible with i386:x86-64 output

And because of this, I have not tried the final line of compilation.

Here is the code for the test.ld file.

ENTRY(main);
SECTIONS
{
    . = 0x7C00;
    .text : AT(0x7C00)
    {
        *(.text);
    }
    .sig : AT(0x7DFE)
    {
        SHORT(0xaa55);
    }
} 

Any suggestions on how to fix this?

BigBerger
  • 1,765
  • 4
  • 23
  • 43

3 Answers3

17

Supply -m32 instead of -march=i686.

fuz
  • 88,405
  • 25
  • 200
  • 352
  • I did this and it works, however there are two more lines of compilation that are given in the tutorial. The second line 'ld -static -Ttest.ld -nostdlib --nmagic -o test.elf test.o' gives me the error of 'ld: i386 architecture of input file `test.o' is incompatible with i386:x86-64 output'. I've made the edit's to the question with the ld code for you to see – BigBerger Dec 28 '14 at 19:34
  • 2
    Supply `-melf_i386` to the `ld` invocation. – fuz Dec 28 '14 at 20:36
6

in fact add -m32 you can keep -march=i686 ...

gcc -c -g -Os -march=i686 -m32 -ffreestanding -Wall -Werror test.c -o test.o

works

gcc -c -g -Os -march=i686 -m16 -ffreestanding -Wall -Werror test.c -o test.o

works

gcc -c -g -Os -march=i686 -m64 -ffreestanding -Wall -Werror test.c -o test.o

fails with ;

test.c:1:0: error: CPU you selected does not support x86-64 instruction set asm(".code16\n");

philippe lhardy
  • 3,096
  • 29
  • 36
-2
gcc -std=c99 -c -g -Os -march=i686 -m32 -ffreestanding -Wall -Werror test.c -o test.o
ld -static -T test.ld -m elf_i386 -nostdlib --nmagic -o test.elf test.o
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
attila
  • 1
  • 2
    This answer doesn't add anything new. It seems to be an attempt to summarize all the advice in the other answers. – Peter Cordes Feb 18 '16 at 20:48