为什么C中的某些函数具有下划线前缀? [英] Why do some functions in C have an underscore prefix?

查看:179
本文介绍了为什么C中的某些函数具有下划线前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始用C语言学习网络,我看到一些以下划线开头的函数-_function()-到底是什么意思?我也看到了这个:

I recently started learning networking in C and I saw some functions that start with an underscore- like _function()- what does that mean exactly? I also saw this :

 struct sockaddr_in  {  

__SOCKADDR_COMMON (sin_);  

 in_port_t sin_port;    

 struct in_addr sin_addr;    

 unsigned char sin_zero[sizeof (struct sockaddr) - 

 __SOCKADDR_COMMON_SIZE -  

sizeof (in_port_t) -         

sizeof (struct in_addr)];  

};

这部分代码是什么意思:

what does this parts of the code mean:

__SOCKADDR_COMMON (sin_);

unsigned char sin_zero[sizeof (struct sockaddr) - 

 __SOCKADDR_COMMON_SIZE -  

sizeof (in_port_t) -         

sizeof (struct in_addr)];

推荐答案

下划线前缀保留给编译器和标准库使用的函数和类型.标准库可以自由使用这些名称,因为它们永远不会与正确的用户程序冲突.

The underscore prefix is reserved for functions and types used by the compiler and standard library. The standard library can use these names freely because they will never conflict with correct user programs.

另一方面,不允许您定义以下划线开头的名称.

The other side to this is that you are not allowed to define names that begin with an underscore.

嗯,这就是规则的要旨.实际规则是这样的:

Well, that is the gist of the rule. The actual rule is this:

  • 您不能在全局范围内定义任何名称以下划线开头的标识符,因为这些标识符可能与隐藏的(私有)库定义冲突.因此,这在您的代码中无效:

  • You cannot define any identifiers in global scope whose names begin with an underscore, because these may conflict with hidden (private) library definitions. So this is invalid in your code:

#ifndef _my_header_h_
#define _my_header_h_ // wrong
int _x; // wrong
float _my_function(void); // wrong
#endif

但这是有效的:

#ifndef my_header_h
#define my_header_h // ok
int x; // ok
float my_function(void) { // ok
    int _x = 3; // ok in function
}
struct my_struct {
    int _x; // ok inside structure
};
#endif

  • 您不能在任何范围内定义名称以两个下划线或一个下划线大写字母开头的标识符.所以这是无效的:

  • You cannot define any identifiers in any scope whose names begin with two underscores, or one underscore followed by a capital letter. So this is invalid:

    struct my_struct {
        int _Field; // Wrong!
        int __field; // Wrong!
    };
    void my_function(void) {
        int _X; // Wrong!
        int __y; // Wrong!
    }
    

    但这没关系:

    struct my_struct {
        int _field; // okay
    };
    void my_function(void) {
        int _x; // okay
    }
    

  • 实际上还有更多的规则,只是为了使事情变得复杂,但上述规则最常被违反,最容易记住.

    There are actually a few more rules, just to make things complicated, but the ones above are the most often violated and the easiest to remember.

    这篇关于为什么C中的某些函数具有下划线前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆