简体   繁体   English

C ++ Makefile未链接

[英]C++ makefile not linking

EXENAME = prog1    
OBJS = link.o main.o

CXX = clang++
CXXFLAGS = -Wall -Wextra

LD = clang++

all : $(EXENAME)

$(EXENAME) : $(OBJS)
    $(LD) $(OBJS) -o $(EXENAME)

main.o : link.h main.cpp 
    $(CXX) $(CXXFLAGS) main.cpp

link.o : link.h link.cpp
    $(CXX) $(CXXFLAGS) link.cpp

clean :
    -rm -f *.o $(EXENAME)

This is the make file I got but all the function in link can't be called in main. 这是我得到的make文件,但是链接中的所有功能都不能在main中调用。 I tried many different ways doesn't work. 我尝试了许多不可行的方法。 This works 这有效

prog1: main.cpp link.h link.cpp
    clang++ -Wall -Wextra -o prog1 main.cpp link.cpp

But I suppose is not the right way to do this? 但是我想这不是正确的方法吗?

It would help if you provided at least some of the errors you got (probably the first few). 如果您至少提供了一些错误(可能是前几个错误),将很有帮助。

Your compiler invocation for building object files is wrong. 您用于构建目标文件的编译器调用是错误的。 Without any other flags specified, the compiler will try to take all the input files and create an executable out of them. 如果未指定任何其他标志,则编译器将尝试获取所有输入文件并从中创建可执行文件。 So this rule: 所以这条规则:

main.o : link.h main.cpp 
        $(CXX) $(CXXFLAGS) main.cpp

expands to this compilation line: 扩展到以下编译行:

clang++ -Wall -Wextra main.cpp

The compiler will attempt to compile and link the main.cpp file (only, because that's all that's listed here) into an executable named a.out (by default). 编译器将尝试编译main.cpp文件并将其链接 (仅限于此,因为此处列出的全部内容) 并链接到名为a.out的可执行文件中(默认情况下)。

You need to add the -c option to your compile lines if you want to build an object file rather than link a program: 如果要构建目标文件而不是链接程序,则需要在编译行中添加-c选项:

main.o : link.h main.cpp 
        $(CXX) $(CXXFLAGS) -c main.cpp

Ditto for building link.o . 同上来建立link.o

Even better would be to simply use make's built-in rules for compiling object files rather than writing your own; 更好的办法是简单地使用make的内置规则来编译目标文件,而不是编写自己的规则。 in that case your entire makefile could just be: 在这种情况下,整个makefile可能只是:

EXENAME = prog1    
OBJS = link.o main.o

CXX = clang++
CXXFLAGS = -Wall -Wextra

all : $(EXENAME)

$(EXENAME) : $(OBJS)
        $(CXX) $(CXXFLAGS) $(OBJS) -o $(EXENAME)

main.o : link.h
link.o : link.h

clean :
        -rm -f *.o $(EXENAME)

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

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