Search code examples
c++makefile

How to create a .o file in a specific folder - Makefile?


Problem :

I need to create .o files in a specific folder. But right know they are just been created in the same folder as my main.cpp.

Makefile :

cversion = -std=c++23
true = 1
false = 0
notfalse = 1
ClassPath = ./test
dotO = ./dotO

output.exe: message.o main.o
    g++ $(cversion) main.o message.o -o output

main.o: main.cpp
    g++ $(cversion) -c main.cpp

message.o: message.cpp
    g++ $(cversion) -c message.cpp

clean:
    @cls
    @echo Errasing...
    @del *.o 
    @del output.exe
    @echo Files have been erased.

message.h :

int messageBox(int x, int y);

message.cpp :

int messageBox(int x, int y){
    return x+y;
}

main.cpp :

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

int main(){
    std::cout << messageBox(10, 50) << std::endl;
}

Important details :

OS : Windows
Text Editor : VScode
I am using mingw64 

Solution

  • If you want them in a specific folder, you need to put them there and use them from there. So to put them in a folder called folder you need something like:

    output.exe: folder/message.o folder/main.o
        g++ $(cversion) folder/main.o folder/message.o -o output
    
    folder/main.o: main.cpp
        g++ $(cversion) -c main.cpp -o $@
    
    folder/message.o: message.cpp
        g++ $(cversion) -c message.cpp -o $@
    

    The above just adds folder/ every time a name for a file that should be in folder is mentioned. You can simplify that a bit by GNU-make using a pattern rule (if you're using GNU make) and $^ to avoid repeating all the dependencies

    output.exe: folder/message.o folder/main.o
        g++ $(cversion) $^ -o output
    
    folder/%.o: %.cpp
        g++ $(cversion) -c $< -o $@
    

    These use the single character "helper" variables that are defined in every rule:

    • $@ the target of the current rule
    • $^ the dependencies of the current rule
    • $< the first dependency of the current rule