How to call a C program in shell script?

前端 未结 3 663
心在旅途
心在旅途 2020-12-10 08:13

I have a simple question. I want to execute a C program in a shell script. How do I do that? Thanks for your help in advance.

相关标签:
3条回答
  • 2020-12-10 08:45

    Almost every program that you execute in a shell script is a C program (but some, often many, of the commands you execute may be built into the shell). You execute a C program in the same way as any other program:

    • By basename: command [arg1 ...]
      • The command must be in a directory searched by the shell - on your PATH, in other words.
    • By relative name: ./command [arg1 ...] or ../../bin/command [arg1 ...]
      • The program must exist and be executable (by you)
    • By absolute name: /some/directory/bin/command [arg1 ...]
      • The program must exist and be executable (by you)

    One of the beauties of Unix is that programs you create, whether in C or any other language, attain the same status as the system-provided commands. The only difference is that the system-provided commands are in a different place (such as /bin or /usr/bin) from commands you create (such as usr/local/bin or $HOME/bin).

    0 讨论(0)
  • 2020-12-10 08:53
    cc hello_world.c #produces a.out
    ./a.out #run your program
    

    IMHO, your problem is the $PATH. Your current directory is not in PATH, so when you enter

    a.out
    

    your shell respond:

    -bash: a.out: command not found
    

    you should execute it as

    ./a.out
    

    (or add "." to your PATH, but this is not recommended.)

    0 讨论(0)
  • 2020-12-10 09:01

    Assuming this is linux/unix we're talking about:

    #!/bin/sh
    /path/to/executable arg1 arg2
    
    0 讨论(0)
提交回复
热议问题