`bash: ./a.out: No such file or directory` on running executable produced by `ld`

后端 未结 3 1685
温柔的废话
温柔的废话 2020-12-15 23:57

Here is a Hello World code in C:

// a.c
#include 

int main() {
    printf(\"Hello world\\n\");
    return 0;
}

I compile it

3条回答
  •  孤城傲影
    2020-12-16 01:01

    ld -lc a.o

    There are several things wrong with this command line:

    1. In general, user-level code should never use ld directly, and always use appropriate compiler front end (gcc here) to perform the link.

      As you have discovered, the link command line that gcc constructs is quite complicated, and the command line that you've accepted in Joan Esteban's answer is wrong.

      If you want to see the actual link command, examine output from gcc -v a.o.

      Also note that link command changes significantly when you change gcc command only slightly (e.g. some OSes require different crt1.o depending on whether you are linking multi-threaded executable or not), and the command line is always OS-specific (which is one more reason to never use ld directly).

    2. Libraries should follow object files on command line. So ld -lc a.o is never correct, and should always be (a variant of) ld a.o -lc. Explanation.

提交回复
热议问题