【问题标题】:How do I change output of C program without editing it? [duplicate]如何在不编辑的情况下更改 C 程序的输出? [复制]
【发布时间】:2014-11-02 20:03:14
【问题描述】:

我有一个不允许编辑的 C 程序,如下所示:

#include <stdio.h>

#ifndef YEAR
 #define YEAR "2013"
#endif

int main(){
  printf("Hello world from " YEAR "\n");
  return 0;
}

我需要创建一个makefile来编译这个程序并将YEAR更改为2014,这样输出将是“Hello world from 2014”而不用编辑C程序。我该怎么做?

【问题讨论】:

  • 手册中有——linux.die.net/man/1/gcc
  • 查看编译器的-D 选项。
  • 能否请 OP 发布此作业的大学和班级编号?我只是好奇。
  • 它来自布加勒斯特波罗泰尼卡大学。
  • 感谢您的回答。我看到我的问题之前已经得到了回答。对此感到抱歉。

标签: c makefile


【解决方案1】:

编译命令应以gcc -Wall -DYEAR='"2014"' 开头。您可以使用合适的CFLAGS 设置对Makefile 进行编码。 This answer 应该是励志的。

【讨论】:

    【解决方案2】:

    只需传递带有 -D 参数的预处理器指令,例如:

    $ cat tmp.c 
    #include <stdio.h>
    
    #ifndef YEAR
     #define YEAR "2013"
    #endif
    
    int main(){
      printf("Hello world from " YEAR "\n");
      return 0;
    }
    
    $ gcc -DYEAR=\"1234\" tmp.c -o tmp && ./tmp
    Hello world from 1234
    

    【讨论】:

    • 它是C代码(不是C++),所以tmp.c作为源文件(不是tmp.cpp)和gcc作为编译器(不是g++)。
    • Basile Starynkevitch,你是对的。更新了答案。
    猜你喜欢
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2019-12-08
    • 2020-03-27
    • 2013-05-09
    • 1970-01-01
    • 2011-08-14
    相关资源
    最近更新 更多