作者:装配脑袋
链接:https://www.zhihu.com/question/40929777/answer/90029159
来源:知乎
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
地方就在不久之前,无论是VC6还是VS2015都不适合学习C语言,因为两者对C根本没有好好支持,都是针对C++的IDE。然而最近VS2015 Update 1新增了用clang作为前端的选项,它对C99有良好的支持,再加上VS方便的编辑调试体验,你终于可以享受了。
新建项目后,打开项目属性,然后在toolset中选取clang即可。
补充一下具体操作,首先你需要安装Visual Studio with Update 1,选择自定义安装,然后选中以下两项:
和
接下来我们只要在Visual C++的项目中即可使用clang的前端了。
实际上VC也支持大部分的C99特性,但是少数特性不支持。我们下面的例子中就有VC本身不支持的C99特性:
#include "stdio.h"
struct point
{
int x;
int y;
};
/* C99特性:restrict指针提示编译器该指针是访问所指目标的唯一方式 */
static inline void swap_int(int * restrict p1, int * restrict p2)
{
// 不要这样实现(C99特性://开头的注释)
*p1 = *p1 ^ *p2;
*p2 = *p1 ^ *p2;
*p1 = *p1 ^ *p2;
}
/* C99特性:static inline函数 */
static inline void swap_point(struct point * p1, struct point* p2)
{
swap_int(&p1->x, &p2->x);
swap_int(&p1->y, &p2->y);
}
int main()
{
struct point p =
{
.x = 2,
.y = 3
};
/* C99特性:复合型字面量 */
swap_point(&p,
&((struct point) { .x = -5, .y = 2 }));
printf("After swap, the point is (%d, %d)\n", p.x, p.y);
if (p.y <= 0) return 0;
/* C99特性:变长数组 */
int vla[p.y];
vla[p.y - 1] = 20;
printf("The length of vla is %d\n", sizeof(vla) / sizeof(int));
return 0;
}
保存为扩展名为.c的文件后,如果用VC来编译,会出现数个编译错误。这是因为restrict被VC用于C++ AMP特性了,并非C99当中的restrict指针。另外变长数组特性也是不支持的。现在我们只要打开项目属性,找到Platform Toolset这一选项,选为Clang前端+C2后端的组合:
再次编译该项目,就能完全编译通过,正确运行了!