C与C++关于函数参数列表为空的异同

2012-05-28 20:12:23

今天在测试socket式IPC时,发现一个问题,一个文件以.c为后缀下可以用gcc编译过,以.cpp为命令则不可以。后来发现C与C++在一些标准上是不一样的。经查,这里应该注意几个问题:

  1. gcc认为.cpp文件是c++文件,并且当做C++程序来进行编译。

  2. g++编译时也用gcc,链接时用g++的链接库。而gcc编译C++程序时候,默认用c的链接库,如果要指定c++的链接库,可以手动指定:gcc -lstdc++

  3. C语言中在申明函数时:

    int foo();//表示函数可以有多个参数

    int foo(void);//表示函数没有参数

  4. C++在申明函数时候,以上两种都表示没有参数。

因此,为了保持可移植性,建议C/C++程序在声明无参函数时,都用int foo(void)这种写法。


参考:http://david.tribble.com/text/cdiffs.htm#C99-func-vararg


Empty parameter lists 
distinguishes between a function declared with an empty parameter list and a function declared with a parameter list consisting of only void. The former is an unprototyped function taking an unspecified number of arguments, while the latter is a prototyped function taking no arguments. 

    // C code

    extern int  foo();          // Unspecified parameters
    extern int  bar(void);      // No parameters

    void baz()
    {
        foo(0);         // Valid C, invalid C++
        foo(1, 2);      // Valid C, invalid C++

        bar();          // Okay in both C and C++
        bar(1);         // Error in both C and C++
    } 
C++, on the other hand, makes no distinction between the two declarations and considers them both to mean a function taking no arguments. 

    // C++ code

    extern int  xyz();

    extern int  xyz(void);  // Same as 'xyz()' in C++,
                            // Different and invalid in C 
For code that is intended to be compiled as either C or C++, the best solution to this problem is to always declare functions taking no parameters with an explicit void prototype. For example: 

    // Compiles as both C and C++
    int bosho(void)
    {
        ...
    } 
Empty function prototypes are a deprecated feature in C99 (as they were in C89). 

[C99: §6.7.5.3
[C++98: §8.3.5, C.1.6.8.3.5]