Hello World in C++ with Emacs

October 6, 2020


This simple exercise shows you what's involved in writing, compiling, and running a simple C++ program using emacs.

  1. Open an Emacs window by clicking on the Emacs icon on your desktop.
  2. Create an empty file called hello.cpp to contain your C++ program. In Emacs, pull down the Files menu and select Open File. A prompt will appear at the bottom of the window. Type hello.cpp and then press the Enter key.

  3. Use your mouse to copy and paste the following C++ program into your Emacs buffer. Simply drag the mouse over the program with the left mouse button depressed to highlight it, then put the mouse into the Emacs window and click the middle mouse button.
    #include <iostream>
    #include <string>
    using namespace std;
    
    // A simple name-echoing program.
    // Art Lee, January 8, 2001
    //
    int main () {
        string s;
        cout << "Please enter your name: ";
        getline(cin, s);
        cout << "Hello " << s << endl;
        cout << "Have fun in cs2010...!..." << endl;
        return 0;
    }
    

  4. Save your program to the empty file. Pull down the Files menu in Emacs and choose Save Buffer.

  5. Compile your program. Pull down the Compile menu in Emacs and select Compile This File (Or, equivalently, try M-x, i.e., Esc-x, followed by compile). The compilation command will appear at the bottom of the window. Press the Enter key to start the compilation.

    If, when you try to compile it this way, Emacs tries to compile with the command make -k, you made a mistake during the Emacs installation. (If you try to compile a C program, e.g., hello.c instead of a C++ program, e.g., hello.cpp, it will try make -k. In that case enter the compile command, gcc -g hello.c -o hello -lm, manually. After you try it manually once, from second time on it will do the right thing automatically.)

  6. The Emacs window will split in two. Wait until the lower window says Compilation finished.

  7. Run your program by typing hello into a DOS window. You will have to connect to the directory (folder) where hello.cpp is saved using the DOS command cd.

  8. To learn more on Emacs, try Emacs Tutorial that you can find under the Help menu in Emacs.