How to add header and source files in Code::Block

Problem

An exercise (from Accelerated C++ Chapter 4) that I have come across recently requires me to partition the program. i.e. instead of writing the entire program in one main.cpp file, I need to split to over multiple C++ source files (with extension .cpp) and header files (with extension .h).

Solution

To add C++ source (.cpp) or header (.h) files, do the followings in Code::Block.

  1. File –> New –> File
  2. Select C/C++ source (or C/C++ header)
  3. Click Go
  4. Click “next”
  5. Select C++, then “next”
  6. Set the file path of the C++ source file accordingly (e.g. same location as the main.cpp file). Name the file to xxx.cpp (or xxx.h)
  7. To make the source file compilable, select “Debug” and “Release” under the Add file option. (If forgotten this step, see the “How to set build target” section below)
  8. Now the source file should appear under Workspace –> ProjectName –> Sources
  9. To compile the file, simply right-click the filename, and click “Build file”.

How to set build target

Assuming we have forgotten to perform step 7 above (or for whatever other reasons), we can always set that target again to enable smooth file build.

  1. Right-click the project name
  2. Properties
  3. Build targets tab
  4. Under the Build target files section in bottom right, check the (currently not checked) files, click OK.
  5. Next time when you right-click the file and build file, Code::Block should build the file accordingly.

Leave a reply