zoukankan      html  css  js  c++  java
  • 终端传值给Makefile、Makefile传值给C++代码

    转自:http://www.bubuko.com/infodetail-1184714.html

    终端传值给Makefile,咋传?只需在终端输入以下命令,那么就可以在Makefile文件中放心大担的使用$(abcde)这个变量了,它的值为BBB

     

    fun.h

    #include <iostream>
    
    class Test {
    public:
        void static display(const char *str);
    };
    

    fun.cpp

    #include "fun.h"
    
    void Test::display(const char *str) {
        std::cout <<str;
    }
    

    main.cpp

    #include "fun.h"
    
    int main() {
    #if defined AAA
        Test::display("AAA
    ");
    #elif defined BBB
        Test::display("BBB
    ");
    #else
        Test::display("CCC
    ");
    #endif
        return 0;
    }
    

    makefile

    OBJS = main.o fun.o
    
    test: $(OBJS)
        g++ $(OBJS) -o test
    
    main.o: main.cpp
        g++ -c main.cpp -D$(abcde) -o main.o
    
    fun.o: fun.cpp
        g++ -c fun.cpp -o fun.o
    
    install:
        cp test ~/test
    
    clean:
        rm *.o test
    

    这是一个多文件时编译makefile的例子,可以看到fun.h始终没出现在代码里边,不用疑惑,fun.cpp已经include进来了。

    一、终端传值给Makefile,咋传?只需在终端输入以下命令,那么就可以在Makefile文件中放心大担的使用$(abcde)这个变量了,它的值为BBB

    $make abcde=BBB
    

    二、Makefile文件传变量给C++代码,其实这是属于g++的范畴,和makefile无关,只需在g++上加参数-D即可,如上例的g++ -c main.cpp -D$(abcde) -o main.o,终端通过命令make abcde=BBB传变量给Makefile,Makefile又把该变量传给g++,g++在编译时定义该变量,于是main.cpp就可以使用到这个变量(应该是宏`#define BBB 1),如果只是传了一个变量名而不赋值,它的值就是1,如果想赋值,应该 这样:

    $make abcde=BBB=3
    

    那么g++ -c main.cpp -D$(abcde) -o main.o就会变成:g++ -c main.cpp -DBBB=3 -o main.o,在C++代码中便有:#define BBB 3

  • 相关阅读:
    如何通过转换例程加减前导0
    PA教材提纲 TAW12-2
    Web开发框架趋势
    ASP.NET MVC
    一步步实现Promise
    在Jenkins中使用Git Plugin访问Https代码库失败的问题
    5年从DBA到运维架构总监 — 做对了什么
    Hello又大了一岁
    JavaWeb限流QPS简易框架
    JAVA异常使用_每个人都曾用过、但未必都用得好
  • 原文地址:https://www.cnblogs.com/yanwei-wang/p/8474024.html
Copyright © 2011-2022 走看看