3

(I am using Ubuntu 18.04 x86-64)

These are the two source files of my program:

//main.c
#include "stdio.h"
int sum(int *a, int n);

int array[2] = {1, 2};

int main()
{
        int val = sum(array,2);
        printf("%d\n", val);
        return 0;
}
//sum.c
int sum(int *a, int n)
{
        int i = 0,s =0;
        for(;i<n;i++)
                s+=a[i];
        return s;
}

I generated the executable by the following steps:

# preprocessing
gcc -E main.c -o main.i 
gcc -E sum.c -o sum.i

# compilation
gcc -Og -S main.i -o main.s 
gcc -Og -S sum.i -o sum.s

# assembling
as main.s -o main.o
as sum.s -o sum.o

# linking
ld -o prog sum.o main.o -lc --entry main

But prog can not be run:

$ ./prog
-bash: ./prog: No such file or directory
$ file ./prog
prog: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib/ld6, not stripped
$ stat prog
  File: prog
  Size: 6424        Blocks: 16         IO Block: 4096   regular file
Device: 801h/2049d  Inode: 3153139     Links: 1
Access: (0777/-rwxrwxrwx)  Uid: ( 1000/       u)   Gid: ( 1000/       u)
Access: 2021-01-22 17:41:02.516854257 +0800
Modify: 2021-01-22 17:31:02.969230783 +0800
Change: 2021-01-22 17:40:57.432364965 +0800
 Birth: -

I wonder what went wrong that prevents me from executing the file.

Name Null
  • 390
  • 2
  • 11

1 Answers1

3

If you run ldd prog you will see /lib/ld64.so.1 => /lib64/ld-linux-x86-64.so.2. The loader /lib/ld64.so.1 does not exists and you get a No such file or directory error. If you add --dynamic-linker=/lib64/ld-linux-x86-64.so.2 to your linking options the program can be executed. Also see this answer.

Edit:

You can see the arguments used by gcc by executing gcc -v main.c sum.c -o program. I used that output for finding the missing linking arguments. When linking with ld -o prog sum.o main.o -lc --dynamic-linker=/lib64/ld-linux-x86-64.so.2 /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/Scrt1.o /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/crti.o /usr/lib/gcc/x86_64-linux-gnu/8/crtbeginS.o -lc /usr/lib/gcc/x86_64-linux-gnu/8/crtendS.o /usr/lib/gcc/x86_64-linux-gnu/8/../../../x86_64-linux-gnu/crtn.o there was no segmentation anymore.

Antonio
  • 181
  • 4
  • I added the `--dynamic-linker=/lib64/ld-linux-x86-64.so.2` option and now it can be executed. But it says ```3\n Segmentation fault (core dumped)```. And I wonder what caused the segmentation fault? Is there any other thing missing? The program itself is not logically wrong, and if I use `gcc -o prog1 main.c sum.c` , the resulting `prog1` does not produce `Segmentation fault (core dumped)` – Name Null Jan 22 '21 at 11:20
  • 1
    Maybe a problem with the return value? Anyway, have a look at how [gcc invokes](https://stackoverflow.com/q/14418242/9989141) the linker and what options it passes. A few of those are probably required to link correctly. – Tarmo Jan 22 '21 at 11:29