Terminal & C Programs

Soldato
Joined
12 Jun 2005
Posts
5,361
Hi there,

When I compile a program with C why do I have to execute with the command "./cprogram" instead of just "cprogram" to run it?

I am currently in the directory of "cprogram".

Is there anyway to change it so that it executse with just "cprogram"?

Thanks.
 
It's just the way Linux shells work.

When you execute "cprogram" the shell searches through a list of predefined directories for a binary of that name, it wont search current directories.

The predefined directory list to search is stored in the environmental variable PATH. You can see this list by running "echo $PATH". And you can add your programming directory to this variable if you want, doing so will allow for "cprogram" to execute correctly.

Add directory as follows:

Code:
PATH=$PATH:/path/to/your/code
export PATH

To make this change persistent, add it to ~/.bash_profile
 
Last edited:
As a security measure, the current directory "." is precluded from the path. This is to prevent someone from disguising a program as a system command. Imagine you ran "ls" thinking it was from /usr/bin but in actual fact it ran from the default directory.

But, this is overkill if you're running as a single user.
 
To save time you could just make an alias to compile and execute (if the compiler succeeds) in a oner, e.g.

Code:
$ alias kwik='clang prog.c -o prog && ./prog'
$ kwik
$ kwik
$ kwik
 
Last edited:
Back
Top Bottom