Dealing with header filesĪ major problem with the above approach is that header files are not taken into account.
#How to create makefile for multiple files full
Notice we’ve defined two sets of inputs, then put them together to determine what the full list of object files should be. PHONY : clean clean : rm -f $(OBJFILES) $(OUT) Here’s an example of a complete Makefile, using the first option of using g++ as the C compiler and the linker.ĬFILES = $( wildcard *.c ) CPPFILES = $( wildcard *.cpp ) OBJFILES = $(CFILES.c=.o) $(CPPFILES.cpp=.o) OUT = main I won’t get into the details of this, but this is a useful tool to learn about.
#How to create makefile for multiple files code
One solution is to use extern "C" blocks in your C++ code to ensure your C++ code refers to the unmangled names when necessary. These are not very common cases, but it could happen. However, this fails if you absolutely need to use the C compiler for a certain C file, or if you have object files that were already compiled from a C file using a C compiler earlier. Now, all C files will also be compiled with the C++ compiler, ensuring all symbols are mangled in the same way. When the file using the symbol uses the mangled name but the file defining the symbol doesn’t have the mangled name (as would be the case when calling a C function from a C++ file), the linking will fail. For example, the types of arguments declared for a function are used in constructing the name of the function symbol in the object file. The problem is that C++ compilers typically mangle symbols. Real-world C++ projects tend to use some C code, and there’s one last issue when doing so. Notice how the Makefile is gathering up all. Re-assign CC to g++ (or to $CXX) so the C++ compiler is used for linking.Īdd -lstdc++ to your LDLIBS in order to add the C++ standard library to the linking process.Īn example Makefile for a C++ project may look like this, if you go with the option of adding the C++ standard library to the list of linked libraries:ĬPPFILES = $( wildcard *.cpp ) OBJFILES = $(CPPFILES.cpp=.o) OUT = mainĬFLAGS = -Wall LDLIBS = -lstdc++ -lm $(OUT) : $(OBJFILES). The result is that the C++ standard library is not available. So, the implicit rule for linking still uses CC as the linker. o file, there’s no indication from the file extension that it came from a C++ file. This is analogous to the CC variable.įlags are passed using the CCXFLAGS variable, instead of CFLAGS. The compiler used for C++ files is set using CXX, which defaults to g++. C files (all extensions recognized by GNU Make as C++ files) into. (Note: you can also omit the definition of the CC variable, as the cc executable should point to the system-default compiler anyway.) Building C++ projectsĬompiling C++ files works similarly to compiling C files. LDLIBS = -ldependency1 -ldependency2 $(OUT) : $(OBJFILES). CFILES = $( wildcard *.c ) OBJFILES = $(CFILES.c=.o) OUT = mainĬFLAGS = -Wall -I /additional/include/dir