【问题标题】:Print c with gcc and c++ with g++用 gcc 打印 c 和用 g++ 打印 c++
【发布时间】:2012-09-24 14:25:56
【问题描述】:

谁能告诉如何编写一个程序,当使用 gcc 编译时打印 c ,而使用 g++ 编译时打印 c++

【问题讨论】:

  • 为什么否定,这是一个奇怪的问题吗?
  • 为什么被封为不真实?我会理解重复,但不是这个。
  • 含糊不清。 OP 可能意味着关于问题的 3 件事。
  • 您实际上问了一个有趣问题的基础,该问题将更多地应用于头文件。如果 C 文件具有 .c 扩展名,您知道它是什么,但如果 C 文件中包含头文件,则需要 #if __cplusplus printf("c++"); #else printf("c"); 但是,您不会有头文件调用 print(至少在大多数情况下) )。这种方法使得 C++ 文件不会命名 mangle C 函数,例如从 DLL (Windows) 或 C 库中导入。
  • @akash 否决按钮显示“这个问题没有显示任何研究工作;不清楚或没有用”,第一个是真的。有些人也投了反对票,因为一个问题似乎很基本……恕我直言,这是愚蠢的。

标签: c++ c gcc g++


【解决方案1】:
#ifdef __cplusplus
    printf("c++\n");
#else
    printf("c\n");
#endif

如果您的文件扩展名不正确,您可能会遇到问题。

【讨论】:

    【解决方案2】:

    类似这样的:

    #if __cplusplus
        printf("c++");
    #else 
        printf("c");
    #endif
    

    除非您使用 g++ -x c 进行编译,否则即使使用 g++ 编译,它仍会打印 C。这是一个问题。

    【讨论】:

    • 我认为它缺少#endif
    • 这种格式化预处理器指令的方式让我很困惑。即使我在心里加了#endif。它可能是有效的,但它仍然感觉不对......
    • 我现在已经解决了这些问题
    • 我很好奇。您似乎已投票以“不是真正的问题”结束该问题。但如果这不是一个真正的问题,你是如何回答的?
    • @BenjaminLindley 在我真正理解 OP 的要求之前,我已经这样做了。
    【解决方案3】:

    struct 标签的处理在 C 和 C++ 之间有所不同

    #include<stdio.h>
    
    typedef int T;
    
    int main(void) {
      struct T { int a[2]; };
      puts((sizeof(T) > sizeof(int)) ? "C++" : "C");
      return 0;
    }
    

    【讨论】:

      【解决方案4】:

      使用 C 和 C++ 之间的差异之一。 (在 sizeof(int) == 1 的实现上会做错事)

      #include <stdio.h>
      
      int main()
      {
         printf("c%s\n", (sizeof('a') == 1 ? "++" : ""));
         return 0;
      }
      

      【讨论】:

        【解决方案5】:

        你的问题有点含糊,我认为你的意思不是字面意思how do you print 'C' or 'C++';但我将其阅读为how do you execute a print in either C or C++ depending on the compiler

        假设这是您的要求,您可以尝试一下:

        #ifdef __cplusplus                //If you compiled with g++
        #include <iostream>                 //include c++ headers and namespace
        using namespace std;
        #define PRINT(str)  cout << str;    //print the message with cout
        #else                             //If you compiled with gcc
        #include <stdio.h>                  //include c headers 
        #define PRINT(str)  printf(str);    //print using printf
        #endif 
        
        int main(int argc, char *argv[])
        {
            PRINT("Hello\n");            //Whatever you compiled with, this now works
            return 0;
        }
        

        【讨论】:

        • 如果是这个问题,他可以跳过所有条件预处理器的内容,只使用 printf,因为这两种语言都可用。
        • @BenjaminLindley - OP 可以只使用 printf(),但 OP 缺少 cout 的好处。我现在正在考虑 cout 动态了解类型,这样您就没有多余的 % 字段,从而减少出错的可能性。
        猜你喜欢
        • 2011-08-05
        • 1970-01-01
        • 2018-07-10
        • 1970-01-01
        • 2017-04-07
        • 1970-01-01
        • 1970-01-01
        • 2011-05-13
        • 2017-02-17
        相关资源
        最近更新 更多