user6245072 user6245072 - 1 year ago 69
C++ Question

First attempt at makefiles

I am writing my first second makefile because I need to understand them before I can actually start my C++ project. Here's the files I'm trying to link:


#ifndef TEST_H_DEF
#define TEST_H_DEF

class Test {
int value;
operator int();
Test operator + (Test);



#include "test.h"

Test::Test(int new_value):
value(new_value) {}

Test::operator int() {
return value;

Test Test::operator + (Test other) {
return Test(value + int(other));


#include <iostream>
#include "test.h"

int main() {
Test o1(12);
Test o2(18);
std::cout << int(o1) << '\n';
std::cout << int(o2) << '\n';
std::cout << int(o1 + o2) << std::endl;

And here's my attempt at a (maintainable) makefile:

CC = g++

default: test

#I'm actually using four spaces here on SO
test: main.o test.o
$(CC) -o test main.o test.o

#my issue starts here: what does main.o depends on? My guess is main.cpp only (which is really /storage/emulated...main.cpp)
main.o: main.cpp
$(CC) -o main.o /storage/emulated/0/cpptest/main.cpp

#same with test.o
test.o: test.cpp
$(CC) -o test.o /storage/emulated/0/cpptest/test.cpp

And then? Am I fine now? How do I handle the issue of test.h being updated without make knowing about it?

Also did I get the usage of .h and .cpp files right while writing my files?

Answer Source

The dependency of test.h is for both test.cpp and main cpp:

CC = g++

default: test

test: main.o test.o
    $(CC) -o test main.o test.o

main.o: main.cpp test.h
    $(CC) -o main.o /storage/emulated/0/cpptest/main.cpp

test.o: test.cpp test.h
    $(CC) -o test.o /storage/emulated/0/cpptest/test.cpp

The idea is that if something changes within test.h both test.o and main.o must be remade.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download