gcc programming.
Hi everyone, this is the tenth installment in the Linux programming series. And thank you so much for following it all the way up to this point. Maybe the first nine posts were all about explanations, so you must be a little bored. But don’t worry,. from this point on, we’ll cover the actual coding part. For a starter, here’s the GCC programming environment setup. Don’t worry, it’s easy. Let’s get into it!!
Let’s start coding! But to do so, we need to prepare our coding environment. For a starter, use whatever text editor you like, either emacs or vim.
Environment settings
For the compiler, gcc (GNU Compiler Collection) will be our choice. To check if gcc is already installed on your machine, type the below code:
gcc -dumpversion
Just like in image 01, if the version number is shown, there’s nothing you have to do anymore. Congrats!
And if not, type the below command to install it manually. By the way, this is the Ubuntu environment.
sudo apt get install build-essential
For CentOS, type the below:
sudo yum group install "Developer Tools"
gcc building processes
Here’s a sample code written in C language.
hello.c
#include<stdio.h>
int
main(int argc, char *argv[]) {
printf("Hello World\n");
return 0;
}
In image 02, you can see there’s the hello.c file. by typing gcc hello.c, you can build the program. As you can see, there’s the file a.out.
In image02, the built file is executed, and it prints out ‘Hello World’ as being programmed.
In image03, I’ve actually named the compiled file name by specifying ‘hello’ when compiling the source code.
Command line arguments
Next, we need to talk about command line arguments. Command line arguments are characters you give when executing a program. In the example below, x,y, and z is the command line arguments and there are three of them.
$ echo x y z
argc and argv
Command line arguments are characters that are passed as main()’s arguments.
Take a look at hello.c again.
hello.c
#include<stdio.h>
int
main(int argc, char *argv[]) {
printf("Hello World\n");
return 0;
}
The argc and argv are responsible for command line arguments. argc handles the command line argument’s number, and argv handles the actual command line arguments’ characters (more specifically, an array of characters). The argv’s type is “pointer array for char”.
image04 is argv’s structure and how it receives the arguments.
The first argv[0] actually receives the executed program’s name.
So, argc is always more than 1, and when you handle the command line arguments in your program, you always have to start it from argc[1].
Here’s a sample code:
args.c
#include<stdio.h>
#include<stdlib.h>
int
main(int argc, char *argv[]) {
int i;
printf("argc=%d\n", argc);
for (i = 0; i < argc; i++) {
printf("argv[%d]=%s\n", i, argv[i]);
}
exit(0);
}
Here’s the result of the test execution of the code.
When you surround the arguments with ” “, it will be recognized as one argument.
Finally, it can read files inside a directory and shows their number.