Search code examples
windowspython-2.7makefilepython-c-api

How to use python "include" and "libs" path in a windows makefile to compile all python embedded C++ program in a folder?


Makefile specified in this question, compiling all the cpp programs in a folder but not with python embedded cpp programs.

all: myUB

sourcesC := $(wildcard ../src/*.cpp)

objectsC := $(patsubst %.cpp,%.o,$(sourcesC))

INPATH=-I"C:/Python27/include"

LIBPATH=-L"C:/Python27/libs"-lpython27

myUB:

    @echo 'Building target $@'

    g++ -O0 -Wall -c -g3 -fmessage-length=0 \
        $(sourcesC)

    del *.o

clean:

Solution

  • Your final makefile could look somthing like:

    all: myUB
    
    sourcesC := $(wildcard ../src/*.cpp)
    
    # Not used
    #objectsC := $(patsubst %.cpp,%.o,$(sourcesC))
    
    INC = -IC:\Python27\include
    
    LIBS = -LC:\Python27\libs -lpython27
    
    myUB:
        @echo 'Building target $@'
        g++ -O0 -Wall -g3 -fmessage-length=0 -o myprog.out $(sourcesC) $(INC) $(LIBS)
    
    clean:
        rm myprog.out
    

    update

    For the undefined ref to WinMain(), it means the linker can't find this function in your code. Either you need to include a library/object that contains it or you can define it yourself in a cpp file like:

    #include <windows.h>
    
    int WINAPI (*MyDummyReferenceToWinMain)(HINSTANCE hInstance, ..., int
    nShowCmd ) = &WinMain;
    

    I got the function template from here.

    But this seems to mean that you are creating a windows application instead of a console app which uses int main(...) entry point.

    Update2

    I have made a new makefile to do what you have asked for in your latest comment which seems to be to create one executable per source file - I am assuming each source file has its own main.

    # Build vars
    CXX = g++
    CXX_FLAGS = -O0 -Wall -g3
    INC = -IC:\Python27\includ
    LIBS = -LC:\Python27\libs -lpython27
    
    # Sources
    SRC_DIR=src
    SOURCES = $(wildcard $(SRC_DIR)/*.cpp)
    $(info SOURCES: $(SOURCES))
    
    # Executables
    EXE_DIR=bin
    EXECUTABLES = $(subst $(SRC_DIR)/,$(EXE_DIR)/,$(subst cpp,out,$(SOURCES)))
    $(info EXECUTABLES: $(EXECUTABLES))
    
    $(info ----)
    
    # Directories
    DIRS = $(EXE_DIR)
    
    # Rule to create folders and compile executables
    all: $(DIRS) $(EXECUTABLES)
    
    # Pattern rule to build each executable
    $(EXE_DIR)/%.out : $(SRC_DIR)/%.cpp
        @echo "compiling $< --> $@"
        @$(CXX) $(CXX_FLAGS) -o $@ $< $(INC) $(LIBS)
    
    # Rule to create output dirs
    $(DIRS):
        @echo "Creating output folders"
        @mkdir -p $(EXE_DIR)
    
    # Rule to clean up
    clean:
        @echo "Cleaning"
        @rm -rf $(EXE_DIR)
    

    This should create one executable in the folder bin/ for each source file (.cpp) in folder src/.