链接未在Makefile中完成

Jig*_*asa 4 c++ makefile

我尝试使用文件main.cpp,factorial.cpp,hello.cpp和function.h制作一个Makefile.在Linux命令窗口输入'make',它显示:

g++ -c -o hello main.o factorial.o hello.o
g++: main.o: linker input file unused because linking not done
g++: factorial.o: linker input file unused because linking not done
g++: hello.o: linker input file unused because linking not done
Run Code Online (Sandbox Code Playgroud)

我是第一次制作Makefile.请提出建议可能是什么问题?Makefile包含以下代码 - >

hello: main.o factorial.o hello.o
        g++ -c -o hello main.o factorial.o hello.o

main.o: main.cpp
        g++ -c -o main.o main.cpp

factorial.o: factorial.cpp
        g++ -c -o factorial.o factorial.cpp

hello.o: hello.cpp
        g++ -c -o hello.o hello.cpp
Run Code Online (Sandbox Code Playgroud)

如果你想看到的单个文件内容是:1)main.cpp

#include<iostream>
#include"functions.h"
using namespace std;
int main()
{
    print_hello();
    cout << endl;
    cout << "The factorial of 5 is " << factorial(5) << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

2)hello.cpp

#include<iostream>
#include "functions.h"
using namespace std;

void print_hello()
{
    cout << "Hello World!";
}
Run Code Online (Sandbox Code Playgroud)

3)factorial.cpp

#include "functions.h"

int factorial(int n)
{
    if(n!=1)
    {
        return(n * factorial(n-1));
    }
    else return 1;
}
Run Code Online (Sandbox Code Playgroud)

4)function.h

 void print_hello();  
 int factorial(int n);
Run Code Online (Sandbox Code Playgroud)

Dav*_*rtz 7

告诉它不要链接的-c参数g++:

-c编译或汇编源文件,但不链接.链接阶段根本没有完成.最终输出是每个源文件的目标文件的形式.

你绝对不希望-c这里:

hello: main.o factorial.o hello.o
        g++ -c -o hello main.o factorial.o hello.o
Run Code Online (Sandbox Code Playgroud)


nog*_*ard 5

您还可以使用规则和模式使其更通用:

SRC_DIR = ./src
OBJ_DIR = ./bin/obj
BIN_DIR = ./build/bin

# List all the sources
SRCS = A.cpp B.cpp

# Define the rule to make object file from cpp
$(OBJ_DIR)/%.o : $(SRC_DIR)/%.cpp
    g++ -o $@ $(INCLUDES) $(CPPFLAGS) -c $^

TARGET_BIN = $(BIN_DIR)/test

all : make_dirs $(TARGET_BIN)

$(TARGET_BIN) : $(SRCS:%.cpp=$(OBJ_DIR)/%.o)
    g++ $(LDFLAGS) -o $@ $^ $(LDLIBS)

make_dirs :
    mkdir -p $(OBJ_DIR)
    mkdir -p $(BIN_DIR)
Run Code Online (Sandbox Code Playgroud)

使用这种方法,您有几个好处:

  • 易于使用:您只需指定一次源文件,而不关心每个目标文件的处理:作业由单个规则完成.

  • 更易于维护:每次需要更改编译器或链接器选项时,都要在单个规则中执行,而不是每个转换单元.