Wednesday, August 22, 2012

How to execute a C/C++ program from terminal?

     Software developers and programmers  will get excited when it comes to programming especially linux users who always mess around with open source software they use. Several IDE's are available where code developers and programmers can test their programs in GUI based environment. Since, terminal users will always rely on it for any kind of task, compiling and executing programs is not going to be an exception. With some simple steps in terminal this can be achieved.

Step 1: Creating a directory for programs
    • Open Terminal available under application menu in dash home.
    • Create a folder of your wish say "sampleprograms" to store your programs,
        • mkdir sampleprograms
    • Switch to the sampleprograms directory,
        • cd sampleprograms


Step 2: Writing the c/c++ program
    • Next, we shall try a sample "hello world!!" program.
    • To write the c/c++ program gedit or any text editor can be used.
    • gedit can be invoked from using the command,
        • sudo gedit helloworld.c (for c program)
        • sudo gedit helloworld.cpp (for c++ program) 
    • Press Enter.
    • After typing the program, save it and the close the editor.
    • Now you have finished writing your c/c++ code.




Step 3: 
  • Compiling C program
    • To compile the C program type the following command,
        • gcc -Wall -Werror -W helloworld.c -o helloworld
    • Here,
        •  gcc refers to the C compiler.
        • -Wall,-Werror,-W used to display the errors which may occur. 
        • helloworld.c is the C program.
        • -o helloworld implies that the exe output will be created under the name helloworld.
    • Press Enter.
    • Run the program using the command,
        • ./helloworld
    • Press Enter.

  • Compiling C++ program
    • To compile the C program type the following command,
      • g++ -Wall -Werror -W helloworld.cpp -o helloworldcpp
    • Here,
      •  g++ refers to the C++ compiler.
      • -Wall,-Werror,-W used to display the errors which may occur. 
      • helloworld.cpp is the C++ program.
      • -o helloworldcpp implies that the exe output will be created under the name helloworldcpp.
    • Press Enter.
    • Run the program using the command,
      • ./helloworldcpp
    • Press Enter.

   So, with the help of these simple steps programmers can compile and execute their programs right from the terminal without any trouble.
 

 






No comments:

Post a Comment