Code::Blocks - How to Compile Multiple Source Files

How to link multiple .cpp files in Code::Blocks for a single project?

In the main.cpp include the header file:

#include "Pen.h"

The Pen.h file it's ok.

You need to add the Pen.cpp file to the project tree.

Go to Project -> Add files... and add Pen.cpp



Sample Image

Compiling Multiple source file into the one .o with g++

You can't compile multiple source files to a single object file. Each source file has to be compiled to its own object file.

You have to do it separately for each source file:


g++ -Wno-deprecated -std=c++0x \
-o $Unit_Test_Output_Directory/unit_test1.o \
-c $Unit_Test_Source_Directory/test1.cc

g++ -Wno-deprecated -std=c++0x \
-o $Unit_Test_Output_Directory/unit_test2.o \
-c $Unit_Test_Source_Directory/test2.cc

multiple small programs in one code::blocks project

let's say that your project contains 3 c files and each c file is a separate program and it contains its own main function:

  • program1.c
  • program2.c
  • program3.c

So you can write a Makefile (its name in your computer should be "Makfile"). It will build the program you want separately

This is how your makefile looks:

all: program1 program2 program3

%.o: %.c
$(CC) $(CFLAGS) -c -o $@ $^

program1: program1.o
$(CC) $(LDFLAGS) -o $@ $^

program2: program2.o
$(CC) $(LDFLAGS) -o $@ $^

program3: program3.o
$(CC) $(LDFLAGS) -o $@ $^

clean:
rm -f *.o program1 program2 program3

with the above Makefile you can build each program separetly

example

$ make program1

will build only program1

or you can buil all programs with

$make all

How do I get Code::Blocks to display .h and .cpp files in the same directory?

The Sources and Headers folders that by default appear to contain
respectively the source and header files of a C::B project are virtual
folders that represent the "categories" (header, source) of the files
within.

To disable this virtual organisation of your project:-

  • Right-click on your project icon in the project workspace
  • From the pop-menu select Project tree
  • In the Project tree sub-menu uncheck the item Categorize by file types


Related Topics



Leave a reply



Submit