【问题标题】:Piece of code that compiles with gcc but not g++ [duplicate]使用 gcc 但不是 g++ 编译的一段代码 [重复]
【发布时间】:2010-12-07 00:30:48
【问题描述】:

可能的重复:
Is this a legitimate C++ code?
“C subset of C++” -> Where not ? examples ?

谁能想出一段代码,用 gcc 或任何其他 C 编译器编译,而不编译 g++ 或任何其他 C++ 编译器?

更新: 我的意思不仅仅是关键字

更新2: 谢谢大家的回答。对于 C 和 C++ 之间的细微差别,版主显然没有我那么热情。

更新3: 主持人:您能否按照您的建议将其与我之前关于该主题的问题合并?将这两个问题放在一起非常有意义。

【问题讨论】:

  • 不,自己做作业
  • 也许看起来像,但事实并非如此。这是我刚刚提出的问题的自然延续
  • 你在评论区给出了你问的例子。
  • 我发誓当我问这个问题时他们不在那里
  • @matcheek:很公平,我认为 pts 确实至少编辑过一次评论。

标签: c++ c gcc g++ coding-style


【解决方案1】:
#include <stdlib.h>

int main()
{
    char* s = malloc(128);
    return 0;
}

这将使用 gcc 编译,但不能使用 g++。 C++ 需要来自 void* 的显式转换,而 C 不需要。

【讨论】:

    【解决方案2】:
    int main(int argc, char **class)
    {
        return !argc;
    }
    

    编辑:另一个例子

    int foo();
    int main(void) {
        return foo(42);
    }
    int foo(int bar) {
        return bar - 42;
    }
    

    【讨论】:

    • OK关键字类,但是如果我们忘记关键字关于关键字?
    【解决方案3】:

    试试

    extern int getSize();
    
    int main()
    {
        char x[getSize()];
        x[0] = 0;
    }
    
    int getSize()
    {
         return 4;
    }
    

    记得用严格的标志编译。

    > gcc -pedantic -std=c99 t.c
    > g++ -pedantic t.c
    t.c: In function `int main()':
    t.c:6: error: ISO C++ forbids variable length array `x'
    

    【讨论】:

      【解决方案4】:

      怎么样

      /* 在函数内 */ { 枚举 {foo} 栏; 酒吧++; }

      这似乎是 C++ 设计中一个相当大的突破性变化,但事实就是如此。

      【讨论】:

        【解决方案5】:

        字符大小如何:
        更糟糕的是它可以编译但在运行时产生不同的输出。

        #include <stdio.h>
        
        int main()
        {
            fprintf(stdout, "%s\n", (sizeof('\xFF') == sizeof(char))?"OK":"Fail");
        }
        
        > gcc -pedantic t.c
        > ./a.exe
        Fail
        > g++ -pedantic t.c
        > ./a.exe
        OK
        

        这实际上让我们想知道为什么会这样?

        fprintf(stdout, "%c%c\n", 'A', 'B');
        

        即使对象的大小不同,它也适用于两种编译器。

        【讨论】:

        • 之所以有效,是因为所有“小”整数类型在任何情况下都被提升为int
        【解决方案6】:

        void* 上的指针运算:

        void* t;
        t++; // compiles only in gcc
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-07-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多