代码之家  ›  专栏  ›  技术社区  ›  Robert Mills

Mac OS上的“cc-std=c99”和“c99”有什么区别?

  •  4
  • Robert Mills  · 技术社区  · 15 年前

    给定以下程序:

    /*  Find the sum of all the multiples of 3 or 5 below 1000. */
    
    #include <stdio.h>
    
    unsigned long int method_one(const unsigned long int n);
    
    int
    main(int argc, char *argv[])
    {
            unsigned long int sum = method_one(1000000000);
            if (sum != 0) {
                    printf("Sum: %lu\n", sum);
            } else {
                    printf("Error: Unsigned Integer Wrapping.\n");
            }
    
            return 0;
    }
    
    unsigned long int
    method_one(const unsigned long int n)
    {
            unsigned long int i;
            unsigned long int sum = 0;
            for (i=1; i!=n; ++i) {
                    if (!(i % 3) || !(i % 5)) {
                            unsigned long int tmp_sum = sum;
                            sum += i;
                            if (sum < tmp_sum)
                                    return 0;
                    }
            }
    
            return sum;
    }
    

    在Mac OS系统(Xcode 3.2.3)上,如果我使用 cc 用于使用 -std=c99 标记一切似乎都正常:

    nietzsche:problem_1 robert$ cc -std=c99 problem_1.c -o problem_1
    nietzsche:problem_1 robert$ ./problem_1 
    Sum: 233333333166666668
    

    但是,如果我使用 c99 要编译它,将发生以下情况:

    nietzsche:problem_1 robert$ c99 problem_1.c -o problem_1
    nietzsche:problem_1 robert$ ./problem_1 
    Error: Unsigned Integer Wrapping.
    

    你能解释一下这种行为吗?

    2 回复  |  直到 15 年前
        1
  •  12
  •   kennytm    15 年前

    c99 is a wrapper of gcc . 它存在是因为POSIX需要它。 c99型 默认情况下将生成32位(i386)二进制文件。

    cc is a symlink to gcc ,因此它接受任何默认配置 海合会 有。 海合会 默认情况下,在本机体系结构中生成一个二进制文件,即x86_64。

    unsigned long 在OS X上的i386上是32位长,而在x86上是64位长。因此, c99型 将有一个“无符号整数包装”,其中 cc -std=c99 没有。

    你可以强迫 c99型 通过 -W 64 旗帜。

    c99 -W 64 proble1.c -o problem_1
    

    (注:由 海合会 我是说实际的gcc二进制 i686-apple-darwin10-gcc-4.2.1 .)

        2
  •  4
  •   Peter G. McDonald    15 年前

    在Mac OS X下,cc是gcc的符号链接(默认为64位),c99不是(默认为32位)。

    /usr/bin/cc->gcc-4.2

    它们对数据类型使用不同的默认字节大小。

    /** sizeof.c
     */
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv)
    {
       printf("sizeof(unsigned long int)==%d\n", (int)sizeof(unsigned long int));
    
       return EXIT_SUCCESS;
    }
    
    cc -std=c99 sizeof.c
    ./a.out
    sizeof(unsigned long int)==8
    
    
    c99 sizeof.c
    ./a.out
    sizeof(unsigned long int)==4
    
    

    很简单,使用c99编译器时,整型变量溢出(也称为包装)。

    .PMCD。