Goal
- Write a first small shell excecutable in C++ under Linux with a parameter.
- This is an extremely simple how to. You can basically copy and paste the code into your shell. It is meant as a starting point into programming in C++ under Linux.
- Once you are done with it, use your favorite text editor and modify your code to do something useful
- The code creates a simple shell executable with a parameter. The program handles wrong input and prints a string according to the parameter.
Steps
1. create a file
touch hello.cpp
2. and fill it right away
cat > hello.cpp
3. with the C++ code
/*
* Simple HelloWorld with parameter and switch statement
*/
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int option = -1;
if(argc > 1) // first arg is name of executable
option = atoi(argv[1]); // atoi - Converts string to long.
switch(option)
{
case 1:
cout << "Hello World !" << endl;
break;
case 2:
cout << "Bye World !" << endl;
break;
default:
cerr << "Usage: " << argv[0] << " [1|2]" << endl;
}
return 0;
}
* Simple HelloWorld with parameter and switch statement
*/
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int option = -1;
if(argc > 1) // first arg is name of executable
option = atoi(argv[1]); // atoi - Converts string to long.
switch(option)
{
case 1:
cout << "Hello World !" << endl;
break;
case 2:
cout << "Bye World !" << endl;
break;
default:
cerr << "Usage: " << argv[0] << " [1|2]" << endl;
}
return 0;
}
4. press ctrl+c
5. create a makefile to easily compile your code
cat > makefile
then
CC=g++
CFLAGS=-I.
hello: hello.o
$(CC) -o hello hello.o $(CFLAGS)
press ctrl+c
6. compile your code by typing:
make
7. and run it:
./hello
or
./hello 1
or
./hello 2
The last steps give you as output:
./hello
Usage: ./hello [1|2]
./hello 1
Hello World !
./hello 2
Bye World !