C++ makefile 同时分离声明和实现

标签 c++ class makefile

我在我的 main.cpp 中用 C++ 写了一个简单的 SQL 解释器 代码是这样的

#include "lexer.h"
#include "parser.h"
#include "interpreter.h"
using namespace std;
int main(int argc, char* argv[]) {
    //my code
}

在lexer.h、parser.h、interpretor.h中,每一个都包含了同名头文件的类的声明和实现。我的问题是我的makefile应该怎么写才能把声明分开和实现,例如,在 lexer.h 中声明,在 lexer.cpp 中实现?

最佳答案

最简单的方法如下所示

interpreter: main.cc lexer.cc parser.cc interpreter.cc
         g++ -o interpreter main.cc lexer.cc parser.cc interpreter.cc -I

但有时使用不同的目标很有用。 这是因为如果您修改项目中的单个文件,则不必重新编译所有内容,只需重新编译您修改的内容。因此您可以像下面那样做

使用依赖项

all: interpreter

interpreter: main.o lexer.o parser.o interpreter.o
    g++ main.o lexer.o parser.o interpreter.o -o interpreter

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

lexer.o: lexer.cc
    g++ -c lexer.cc

parser.o: parser.cc
    g++ -c parser.cc

interpreter.o: interpreter.cc
    g++ -c interpreter.cc

clean:
    rm -rf *o hello

使用变量和注释 我们也可以在编写 Makefile 时使用变量

# Implementing a new sql lexer the variable CC will be
# the compiler to use.
CC=g++
# these flags will be passed to the compiler.
CFLAGS=-c -Wall
    all: interpreter

    interpreter: main.o lexer.o parser.o interpreter.o
        $(CC) main.o lexer.o parser.o interpreter.o -o interpreter

    main.o: main.cc
        $(CC) $(CFLAGS) main.cc

    lexer.o: lexer.cc
        $(CC) $(CFLAGS) lexer.cc

    parser.o: parser.cc
        $(CC) $(CFLAGS) parser.cc

    interpreter.o: interpreter.cc
       $(CC) $(CFLAGS) interpreter.cc

    clean:
        rm -rf *o hello

关于C++ makefile 同时分离声明和实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27738625/

相关文章:

c++ - 尝试将非托管 C++ 类转换为托管 C++ 类时出现奇怪的错误(用于 .net)

java - java中是否可以将变量的值从一个类移动到另一个类而无需继承?

makefile - 无法安装最新的 ejabberd 和 Erlang 版本 Ubuntu 14.04 LTS

c++ - "Request for member which is of non-class type", 赋值语句不正确?

C++文件读取

c++ - 如何在大项目中使用#include?

c++ - 如何以最优雅的C++方式设计一个已经预定义标准颜色的颜色类?

c++ - 如何在 make 期间更改 libtool 调用的 g++ 标志

c++ - Windows下编译RInside例子的问题

javascript - 客户端 - 服务器 Web 应用程序