I've an issue with object creation for a cpp files residing in 2 different directories as show below:
- Project-xyz
- Hello
- Hello.cpp
- World
- Main.cpp
- World.cpp
- Makefile
For better clarity here is how the code looks (just a dummy code).
hello/Hello.h
#ifndef HELLO_H
#define HELLO_H
void HelloPrint();
#endif // HELLO_H
hello/Hell.cpp
#include <iostream>
#include "Hello.h"
void HelloPrint()
{
std::cout <<"Hello" << std::endl;
}
world/World.h
#ifndef WORLD_H
#define WORLD_H
void WorldPrint();
#endif // WORLD_H
world/World.cpp
#include <iostream>
#include "World.h"
void WorldPrint()
{
std::cout <<"World!" << std::endl;
}
world/Makefile Using a makefile given in here. Which is working fine. But it doesn't create any obj files.
# set non-optional compiler flags here
CXXFLAGS += -std=c++11 -Wall -Wextra -pedantic-errors
# set non-optional preprocessor flags here
# eg. project specific include directories
CPPFLAGS +=
# find cpp files in subdirectories
SOURCES := $(shell find . -name '*.cpp')
SOURCES += $(shell find ../hello -name '*.cpp')
# find headers
HEADERS := $(shell find . -name '*.h')
OUTPUT := HelloWorld
# Everything depends on the output
all: $(OUTPUT)
# The output depends on sources and headers
$(OUTPUT): $(SOURCES) $(HEADERS)
$(CXX) $(CXXFLAGS) $(CPPFLAGS) -o $(OUTPUT) $(SOURCES)
clean:
$(RM) $(OUTPUT)
I'm looking at a solution which uses the makefile which generates the obj files in specific directory as shown here.
Now I'm trying to generate the obj files for hello/hello.cpp file in world/objdir/hello.o using the Below make file. Which is not working. How to get it working?
world/Makefile
GCC=g++
CPPFLAGS=-c -Wall
LDFLAGS=
OBJDIR=objdir
OBJ=$(addprefix $(OBJDIR)/, $(patsubst %.cpp, %.o, $(wildcard *.cpp)))
TARGET=HelloWorld
.PHONY: all clean
all: $(OBJDIR) $(TARGET)
$(OBJDIR):
mkdir $(OBJDIR)
$(OBJDIR)/%.o: %.cpp
$(GCC) $(CPPFLAGS) -c $< -o $@
$(TARGET): $(OBJ)
$(GCC) $(LDFLAGS) -o $@ $^
clean:
@rm -f $(TARGET) $(wildcard *.o)
@rm -rf $(OBJDIR)
When i try to run the make it throws the following error.
g++ -c -Wall -c main.cpp ../hello/Hello.cpp -o objdir/main.o
g++: fatal error: cannot specify -o with -c, -S or -E with multiple files
compilation terminated.
make: *** [objdir/main.o] Error 4
It is not able to generate the obj files for the hello/Hello.cpp file and hence throwing this error.
Any help from the makefile Masters is appreciated! :)