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

Rob*_*lls 5 c compiler-construction xcode c99

鉴于以下计划:

/*  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;
}
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

但是,如果我用c99它来编译它会发生这种情况:

nietzsche:problem_1 robert$ c99 problem_1.c -o problem_1
nietzsche:problem_1 robert$ ./problem_1 
Error: Unsigned Integer Wrapping.
Run Code Online (Sandbox Code Playgroud)

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

ken*_*ytm 12

c99是一个包装gcc.它存在是因为POSIX需要它.c99默认情况下会生成32位(i386)二进制文件.

cc是一个符号链接gcc,因此它采用默认配置gcc.gcc默认情况下,在本机体系结构中生成二进制文件,即x86_64.

unsigned long在OS X上的i386上是32位长,在x86_64上是64位长.因此,c99将有一个"无符号整数换行",cc -std=c99但没有.

您可以c99通过-W 64标志强制在OS X上生成64位二进制文​​件.

c99 -W 64 proble1.c -o problem_1
Run Code Online (Sandbox Code Playgroud)

(注意:gcc我的意思是实际的gcc二进制文件i686-apple-darwin10-gcc-4.2.1.)


Pet*_*ald 5

在 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));

   返回退出成功;
}

cc -std=c99 sizeof.c
./a.out
sizeof(unsigned long int)==8


c99 sizeof.c
./a.out
sizeof(unsigned long int)==4

很简单,在使用 c99 编译器时,您正在溢出(又名包装)您的整数变量。

.PMCD。