How do I run .c file from the command line

41,654

Solution 1

C is not an interpreted language like Python or Perl. You cannot simply type C code and then tell the shell to execute the file. You need to compile the C file with a C compiler like gcc then execute the binary file it outputs.

For example, running gcc file.c will output a binary file with the name a.out. You can then tell the shell to execute the binary file by specifying the files full path ./a.out.

Edit:
As some comments and other answers have stated, there are some C interpreters that exist. However, I would argue that C compilers are more popular.

Solution 2

If you have a single foo.c, see if make can compile it for you:

make foo

No makefiles or anything needed.

Solution 3

tcc -run file.c will sometimes run a .c file. If the .c file needs additional libraries, tcc -llib1 -llib2 ... -run file.c will succeed. Sometimes it just won't work. tcc is not gcc.

Incidentally, you can put #!/usr/bin/tcc -run on the top of a .c file, chmod +x the file, and run it like any other script. When the .c file works in tcc, this behaves itself just fine.

Simple .c files from someone new to C will almost always work.

Solution 4

I am beginning to work with micro controllers and programming them using C language.

In practice, that is an important consideration. I'm guessing that your microcontroller is something like an Arduino (or perhaps a Raspberry Pi).

In general, you need some cross-compiler. You'll then cross-compile, on your desktop system (e.g. some Linux, which is very developer friendly; but you can find cross-compilers hosted on Windows or MacOSX, for Arduinos), your source code into an executable targetted for your microcontroller and later transmit the binary executable to your microcontroller.

C is a difficult programming language.

In many cases, you might compile directly your code on your desktop (don't forget to enable all warnings and debug info, e.g. gcc -Wall -Wextra -g with GCC), test most of it on your desktop, and later adapt it and port it for your Arduino. Debugging on your laptop or desktop some code is a lot easier than debugging on your Arduino.

You'll later cross-compile the same source code for your microcontroller.

Share:
41,654
Iam Pyre
Author by

Iam Pyre

Updated on September 18, 2022

Comments

  • Iam Pyre
    Iam Pyre over 1 year

    I am beginning to work with micro controllers and programming them using C language.

    All my programming experience is with Python language.

    I know that if I want to test a script I have written in python, I can simply launch terminal and type in “python” with the path of the file I want to run.

    I tried a web search, but most didn’t seem to understand what I was asking.

    How do I run c from terminal?

  • user253751
    user253751 about 6 years
    tcc is just compiling it for you then, right?
  • Joshua
    Joshua about 6 years
    @immibis: tcc compiles into RAM and runs immediately.