Makefile that compiles all cpp files in a directory into separate executable

前端 未结 4 1247
不知归路
不知归路 2021-02-09 01:12

I am now studying C++. I want a makefile which will compile all of the cpp files in the current directory to separate executables. For example:

相关标签:
4条回答
  • 2021-02-09 01:42

    A minimal Makefile that does what you want would be:

    #Tell make to make one .out file for each .cpp file found in the current directory
    all: $(patsubst %.cpp, %.out, $(wildcard *.cpp))
    
    #Rule how to create arbitary .out files. 
    #First state what is needed for them e.g. additional headers, .cpp files in an include folder...
    #Then the command to create the .out file, probably you want to add further options to the g++ call.
    %.out: %.cpp Makefile
        g++ $< -o $@ -std=c++0x
    

    You'll have to replace g++ by the compiler you're using and possibly adjust some platform specific setting, but the Makefile itself should work.

    0 讨论(0)
  • 2021-02-09 01:42

    My answer builds on top of the answer by @Haatschii

    I don't prefer to have the .out prefix to my binaries. Also I used his existing Make syntax to perform clean as well.

    CXX=clang++
    CXXFLAGS=-Wall -Werror -std=c++11
    
    all: $(patsubst %.cpp, %.out, $(wildcard *.cpp))
    
    %.out: %.cpp Makefile
            $(CXX) $(CXXFLAGS) $< -o $(@:.out=)
    
    clean: $(patsubst %.cpp, %.clean, $(wildcard *.cpp))
    
    %.clean:
            rm -f $(@:.clean=)
    
    0 讨论(0)
  • 2021-02-09 01:49

    The simplest makefile you can create that might work for you is this:

    all: examp1.exe examp2.exe examp3.exe
    

    That will use make's default rules to create your three programs.

    0 讨论(0)
  • 2021-02-09 01:53

    This is the Makefile that I use

    CC = gcc
    CFLAGS = -g -O2 -std=gnu99 -static -Wall -Wextra -Isrc -rdynamic -fomit-frame-pointer
    all: $(patsubst %.c, %.out, $(wildcard *.c))
    %.out: %.c Makefile
        $(CC) $(CFLAGS) $< -o $@ -lm
    clean:
        rm *.out                      
    

    You should paste it somewhere in your home and whenever you change the dirctory just copy it there. I use an alias in my ~/.basrc to copy it

    alias get_makefile_here='cp ~/Makefile ./'
    

    Simply press make and bam, you're done. Also notice the fact that once you're done with the old files it will not rebuild their executable.

    0 讨论(0)
提交回复
热议问题