c++gccg++makefile

g++ compile source files existing in another directory


I am trying to set up a build process using makefiles, for a C++ plugin that I am working on. I am curious to know if there is any way to make g++ compile source files found in another directory.

My motivation for doing this is to avoid having to specify the relative path for each source file, as I explain below.

My project directory structure looks like:

MyPlugin --> src   --> Foo.cpp
                   --> Foo.h
                   --> Bar.cpp
                   --> Bar.cpp
         --> build --> Makefile

Following is a stripped-down version of my current Makefile:

SRC_PATH=../src
OUT_PATH=../bin
VPATH=${SRC_PATH}
FILES=Foo.cpp Bar.cpp

CC=g++
CFLAGS=-Wall -shared

all:
    mkdir -p ${OUT_PATH}
    ${CC} ${CFLAGS} -I${SRC_PATH} ${FILES} -o ${OUT_PATH}/MyPlugin.so

By doing this, I am trying to avoid defining the FILES variable as below:

FILES=../src/Foo.cpp ../src/Bar.cpp

When I tried running make all, g++ gave me an error. It looks like the path specified through the -I flag is only used to search for #included files.

g++: Foo.cpp: No such file or directory
g++: Bar.cpp: No such file or directory

I cannot use wildcards (*.cpp), because I do not always want all the files to be picked up for compilation. Another alternative is to cd to the src directory, as mentioned here, and run g++ from there, but that only works for me if all the files are in the same directory (I need the output to be a single .so file). I also tried setting the environment variable PATH, but that didn't seem to have any effect.

I have looked into the g++ help, the make documentation, and looked at Stack Overflow posts, such as https://stackoverflow.com/questions/10010741/g-compile-with-codes-of-base-class-in-a-separate-directory and gcc/g++: "No such file or directory", but I could not find any solution which I could use. Is there a suitable approach to this problem?

The example may have been misleading. In this stripped-down example, I have all the source files in one directory, but in my actual project, I have several subdirectories, and multiple files in each directory. Thus, although cding to the src directory works in my above example, it won't work in my actual project (or at least, I would like to know how it would work).


Solution

  • You can have second variable for the actual source files, like this:

    FILES = Foo.cpp Bar.cpp
    SOURCES = $(FILES:%.cpp=$(SRC_PATH)/%.cpp)
    

    Then instead of using FILES when building you use SOURCES.