Banner image

bar.h

#ifndef __myproject_h__
#define __myproject_h__

int getX();

#endif

bar.cpp

#include <iostream>
#include "bar.h"
using namespace std;

int getX() {
  cout << "getX accessed" << endl;
  return 10;
}

foo.cpp

#include <iostream>
#include "bar.h"
using namespace std;

int main() {
  cout << "Hello World!" << endl;
  int x = getX();
  cout << "Value of x: " << x << endl;
  return 0;
}

Makefile

CXX = g++
CFLAGS = -Wall
LDFLAGS =
OBJFILES = foo.o bar.o
TARGET = foobar
all: $(TARGET)
$(TARGET): $(OBJFILES)
<TAB>$(CXX) $(CFLAGS) -o $(TARGET) $(OBJFILES) $(LDFLAGS)

.PHONY: clean
clean:
<TAB>rm -f $(OBJFILES) $(TARGET) *~

Important: Replace <TAB> by an actual tab (spaces won’t do)

Steps:

  1. Store all these files in the same directory, cd into that directory
  2. Run make
  3. Run ./foobar
    The expected output is:

    Hello World!
    getX accessed
    Value of x: 10

  4. To get rid of all the files generated by make, run make clean

Useful notes:

  1. <*.h> is used for standard libraries, "*.h" is used for header files defined in the project.
  2. #ifndef is needed as the header file is called multiple times. This prevents multiple declarations of getX() which would otherwise cause an error.
  3. You can’t have more than 1 main() while building a single target.

Similar quick guide for cmake and CMakeLists.txt