Running C program in UNIX

I want to run a C program from my BASH script. Here's some very basic simplified code of my bash script:

#!/bin/bash
 
echo "Run C program"
./main.c
echo "Ran C program"

Here's my main.c:

#include <stdio.h>
#include <stdlib.h>
 
int main(int argc, char *argv[])
{
  printf("/nRunning C program/n");
}

When I run the script I get the following errors:

# ./cprog.sh
./cprog.sh: #!/bin/bash: not found
Run C program:
./main.c: 4: Syntax error: "(" unexpected
Ran C program
#

Please excuse my ignorance as it has been some time since I have used C. Do I need more than just main.c?
Do I need to do more than just call it using ./main.c from my script?

Thanks

You cannot give the source file directly. Compile your C program and get an exe, and then execute the exe from the shell script.

Like:
Compile your C program:

 
$ cc -o myprog main.c
$ ls myprog
myprog
 
#!/bin/bash

echo "Run C program"
./myprog
echo "Ran C program"

Guru.

1 Like

Thanks Guru. That works. Just wondering why using the exe that was generated using the C compiler doesn't work (as opposed to using the Unix compiled one).

I think you're confusing the concepts. In your original script you were trying to run a flat text file which happened to have a .c extension. Its contents cannot be interpreted by a shell nor by "Unix" (assuming you're referring to the operating system).

So you basically forgot the step where you compile the code before running it.

1 Like