C에서 가장 일반적인 명명 규칙은 무엇입니까?
C에서 일반적으로 사용하는 명명 규칙은 무엇입니까? 나는 적어도 두 가지가 있다는 것을 안다.
- lower_case_functions를 사용한 GNU / 리눅스 / K & R
- ? 이름? UpperCaseFoo 함수 사용
나는 여기서 C에 대해서만 이야기하고 있습니다. 대부분의 프로젝트는 C를 사용하는 소형 임베디드 시스템입니다.
다음 프로젝트에 사용할 계획입니다.
C 명명 규칙
Struct TitleCase
Struct Members lower_case or lowerCase
Enum ETitleCase
Enum Members ALL_CAPS or lowerCase
Public functions pfx_TitleCase (pfx = two or three letter module prefix)
Private functions TitleCase
Trivial variables i,x,n,f etc...
Local variables lower_case or lowerCase
Global variables g_lowerCase or g_lower_case (searchable by g_ prefix)
여기서 가장 중요한 것은 일관성입니다. 즉, GTK + 코딩 규칙을 따르며 다음과 같이 요약 할 수 있습니다.
- 대문자로 된 모든 매크로 및 상수 :
MAX_BUFFER_SIZE
,TRACKING_ID_PREFIX
. - 낙타의 구조 이름 및 typedef :
GtkWidget
,TrackingOrder
. - 구조체에서 작동하는 함수 : classic C style :
gtk_widget_show()
,tracking_order_process()
. - 포인터 : 여기서 멋진 것은 없습니다 :
GtkWidget *foo
,TrackingOrder *bar
. - 전역 변수 : 전역 변수를 사용하지 마십시오. 그들은 악하다.
- 거기에 있지만 직접 호출되거나 모호한 용도로 사용해서는 안되는 함수 또는 시작 부분에 하나 이상의 밑줄 :
_refrobnicate_data_tables()
,_destroy_cache()
.
"구조 포인터"는이를 다루기위한 명명 규칙이 필요한 엔티티가 아닙니다. 그들은 단지 struct WhatEver *
. 영리하고 "명백한"typedef와 관련된 포인터가 있다는 사실을 숨기지 마십시오. 그것은 목적을 제공하지 않으며, 더 이상 타이핑하는 것이 아니며, 선언과 액세스 사이의 균형을 파괴합니다.
우선 C에는 공개 / 개인 / 가상 기능이 없습니다. 그것은 C ++이며 다른 규칙이 있습니다. C에는 일반적으로 다음이 있습니다.
- ALL_CAPS의 상수
- 구조체 또는 함수 이름에서 단어를 구분하기위한 밑줄은 C에서 낙타 문자를 거의 보지 못합니다.
- 구조체, typedef, 공용체, 공용체 및 구조체의 멤버 및 열거 형 값은 일반적으로 첫 번째 문자를 대문자로 만드는 C ++ / Java / C # / etc 규칙보다는 소문자입니다 (내 경험상).하지만 가능할 것으로 생각합니다. C도.
C ++는 더 복잡합니다. 나는 여기에 진짜 믹스를 보았습니다. 클래스 이름이나 소문자 + 밑줄을위한 낙타 케이스 (낙타의 경우는 더 일반적입니다). Structs는 거의 사용되지 않으며 일반적으로 라이브러리에 필요하기 때문에 클래스를 사용합니다.
알다시피, 나는 그것을 간단하게 유지하고 싶지만 분명합니다 ... 그래서 C에서 사용하는 것이 여기 있습니다.
- 사소한 변수 :
i,n,c
, etc ... (한 글자 만. 한 글자가 명확하지 않으면 지역 변수로 만듭니다) - 지역 변수 :
lowerCamelCase
- 글로벌 변수 :
g_lowerCamelCase
- 상수 변수 :
ALL_CAPS
- 포인터 변수 :
p_
접두사 에 a 를 추가 합니다. 전역 변수의 경우gp_var
로컬 변수p_var
의 경우 const 변수가p_VAR
됩니다. 멀리 포인터를 사용하는 경우fp_
대신 을 사용하십시오p_
. - Structs :
ModuleCamelCase
(모듈 = 전체 모듈 이름 또는 2-3 자 약어이지만 여전히CamelCase
.) - 구조체 멤버 변수 :
lowerCamelCase
- 열거 형 :
ModuleCamelCase
- 열거 형 값 :
ALL_CAPS
- 공공 기능 :
ModuleCamelCase
- 개인 기능 :
CamelCase
- 매크로 :
CamelCase
구조체를 typedef하지만 태그와 typedef에 동일한 이름을 사용합니다. 태그는 일반적으로 사용되지 않습니다. 대신 typedef를 사용하는 것이 좋습니다. 또한 캡슐화를 위해 공개 모듈 헤더에 typedef를 선언하여 typedef의 이름을 정의에 사용할 수 있도록합니다.
전체 struct
예 :
typdef struct TheName TheName;
struct TheName{
int var;
TheName *p_link;
};
C #, java, C, C ++ 및 objective C 로 동시에 코딩하면서 , 나는 삶을 단순화하기 위해 매우 간단하고 명확한 명명 규칙을 채택했습니다.
우선, 그것은 현대의 IDE (예 : 일식, Xcode ...)의 힘에 의존하여 호버링 또는 Ctrl 키 클릭으로 빠른 정보를 얻을 수 있습니다 ... 그리고 IDE가 제공하는 다른 마커들.
그런 다음 컨벤션 :
- Any names MUST be a readable sentence explaining what you have. Like "this is my convention".
- Then, 4 methods to get a convention out of a sentence:
- THIS_IS_MY_CONVENTION for macros, enum members
- ThisIsMyConvention for file name, object name (class, struct, enum, union...), function name, method name, typedef
- this_is_my_convention global and local variables,
parameters, struct and union elements - thisismyconvention [optional] very local and temporary variables (such like a for() loop index)
And that's it.
It gives
class MyClass {
enum TheEnumeration {
FIRST_ELEMENT,
SECOND_ELEMENT,
}
int class_variable;
int MyMethod(int first_param, int second_parameter) {
int local_variable;
TheEnumeration local_enum;
for(int myindex=0, myindex<class_variable, myindex++) {
localEnum = FIRST_ELEMENT;
}
}
}
I would recommend against mixing camel case and underscore separation (like you proposed for struct members). This is confusing. You'd think, hey I have get_length
so I should probably have make_subset
and then you find out it's actually makeSubset
. Use the principle of least astonishment, and be consistent.
I do find CamelCase useful to type names, like structs, typedefs and enums. That's about all, though. For all the rest (function names, struct member names, etc.) I use underscore_separation.
Here's an (apparently) uncommon one, which I've found useful: module name in CamelCase, then an underscore, then function or file-scope name in CamelCase. So for example:
Bluetooth_Init()
CommsHub_Update()
Serial_TxBuffer[]
I'm confused by one thing: You're planning to create a new naming convention for a new project. Generally you should have a naming convention that is company- or team-wide. If you already have projects that have any form of naming convention, you should not change the convention for a new project. If the convention above is just codification of your existing practices, then you are golden. The more it differs from existing de facto standards the harder it will be to gain mindshare in the new standard.
About the only suggestion I would add is I've taken a liking to _t at the end of types in the style of uint32_t and size_t. It's very C-ish to me although some might complain it's just "reverse" Hungarian.
You should also think about the order of the words to make the auto name completion easier.
A good practice: library name + module name + action + subject
If a part is not relevant just skip it, but at least a module name and an action always should be presented.
Examples:
- function name:
os_task_set_prio
,list_get_size
,avg_get
- define (here usually no action part):
OS_TASK_PRIO_MAX
There could be many, mainly IDEs dictate some trends and C++ conventions are also pushing. For C commonly:
- UNDERSCORED_UPPER_CASE (macro definitions, constants, enum members)
- underscored_lower_case (variables, functions)
- CamelCase (custom types: structs, enums, unions)
- uncappedCamelCase (oppa Java style)
- UnderScored_CamelCase (variables, functions under kind of namespaces)
Hungarian notation for globals are fine but not for types. And even for trivial names, please use at least two characters.
I think those can help for beginner: Naming convention of variables in c
- You have to use Alphabetic Character (a-z, A-Z), Digit (0-9) and Under Score (_). It’s not allow to use any special Character like: %, $, #, @ etc. So, you can use user_name as variable but cannot use user&name.
- Can not use white space between words. So, you can use user_name or username or username as variable but cannot use user name.
- Can not start naming with digit. So, you can use user1 or user2 as variable but cannot use 1user.
- It is case sensitive language. Uppercase and lowercase are significant. If you use a variable like username then you cannot use USERNAME or Username for father use.
- You can not use any keyword (char, int, if, for, while etc) for variable declaration.
- ANSI standard recognizes a length of 31 characters for a variable name
참고URL : https://stackoverflow.com/questions/1722112/what-are-the-most-common-naming-conventions-in-c
'IT story' 카테고리의 다른 글
Eclipse에서 조건부 중단 점을 사용하는 방법은 무엇입니까? (0) | 2020.07.29 |
---|---|
SynchronizationContext의 기능은 무엇입니까? (0) | 2020.07.29 |
사용 가능한 ID가 없습니다-관리자 요청 (0) | 2020.07.29 |
IntelliJ IDEA가 build.sbt에서 종속성을 변경 한 후 강제로 다시로드하는 방법은 무엇입니까? (0) | 2020.07.29 |
'int main;' (0) | 2020.07.29 |