简体   繁体   English

未定义的参考错误Makefile C ++

[英]undefined reference error Makefile c++

I wrote makefile the way below and get undefined reference error for all functions that are stored in AM.cpp and used in main. 我以下面的方式编写了makefile,并获得了存储在AM.cpp中并在main中使用的所有函数的未定义参考错误。 What do i do wrong? 我做错了什么?

CCX=g++
FLAGS +=-c -Wall -lopenal -lSDL
LINK_FLAGS += -lopenal -lSDL

all: MyExe
MyExe: main.o
    $(CXX) main.o $(LINK_FLAGS) -o MyExe
main.o: main.cpp AM.cpp AB.cpp AS.cpp
    $(CXX) $(FLAGS) main.cpp AM.cpp AB.cpp AS.cpp

You should compile an object for every cpp you have and then in the final linking step you should name all of them. 您应该为每个cpp编译一个对象,然后在最后的链接步骤中为所有它们命名。

Also the libraries only need to be specified in the linker flags. 同样,只需要在链接器标志中指定库。

Like so: 像这样:

CCX=g++
FLAGS +=-c -Wall
LINK_FLAGS += -lopenal -lSDL

all: MyExe
MyExe: main.o AM.o AB.o AS.o
    $(CXX) main.o AM.o AB.o AS.o $(LINK_FLAGS) -o MyExe
main.o: main.cpp
    $(CXX) $(FLAGS) main.cpp
AM.o: AM.cpp
    $(CXX) $(FLAGS) AM.cpp
AB.o: AB.cpp
    $(CXX) $(FLAGS) AB.cpp
AS.o: AS.cpp
    $(CXX) $(FLAGS) AS.cpp

It's also not a bad idea to just create a universal makefile that can be re-used. 仅创建一个可以重复使用的通用makefile也不是一个坏主意。 Mine looks like this: 我的看起来像这样:

CXX=gcc
CXX_FLAGS=-c -O0 -Wall -Wextra
CXX_LFLAGS=-lssl -lcrypto -ldl -liniparser
SOURCES=main.cpp test.cpp ...cpp #add your source files here
OBJECTS=$(SOURCES:.cpp=.o) #takes the .cpp files from the SOURCES var and replaces the .cpp with .o for each
EXEC=yourapp

all: $(SOURCES) $(EXEC)

clean:
    rm -f $(OBJECTS)
    rm -f $(EXEC)

$(EXEC): $(OBJECTS)
    $(CXX) -o $@ $(OBJECTS) $(CXX_LFLAGS) #$@ will be replaced with the content of EXEC, so your applications name

#a build rule for all .cpp files to be compiled to a .o file. % is a placeholder for the actual name of the file
%.o: %.cpp 
    $(CXX) $(CXX_FLAGS) $<  # $< will be replaced with the .cpp file name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM