| 1 |
# C style guide |
| 2 |
|
| 3 |
<!--* |
| 4 |
# Document freshness: For more information, see go/fresh-source. |
| 5 |
freshness: { owner: 'haberman' reviewed: '2022-05-08' } |
| 6 |
*--> |
| 7 |
|
| 8 |
Since upb is written in pure C, we supplement the |
| 9 |
[Google C++ style guide](https://google.github.io/styleguide/cppguide.html) with |
| 10 |
some C-specific guidance. |
| 11 |
|
| 12 |
Everything written here is intended to follow the spirit of the C++ style guide. |
| 13 |
|
| 14 |
upb is currently inconsistent about following these conventions. It is intended |
| 15 |
that all code will be updated to match these guidelines. The priority is |
| 16 |
converting public interfaces as these are more difficult to change later. |
| 17 |
|
| 18 |
## Naming |
| 19 |
|
| 20 |
### Functions and Types |
| 21 |
|
| 22 |
C does not have namespaces. Anywhere you would normally use a namespace |
| 23 |
separator (`::`) in C++, we use an underscore (`_`) in C: |
| 24 |
|
| 25 |
```c++ |
| 26 |
// C equivalent for upb::Arena::New() |
| 27 |
upb_Arena* upb_Arena_New(); |
| 28 |
``` |
| 29 |
|
| 30 |
Since we rely on `_` to be our namespace separator, we never use it to merely |
| 31 |
separate words in function or type names: |
| 32 |
|
| 33 |
```c++ |
| 34 |
// BAD: this would be interpreted as upb::FieldDef::has::default(). |
| 35 |
bool upb_FieldDef_has_default(const upb_FieldDef* f); |
| 36 |
|
| 37 |
// GOOD: this is equivalent to upb::FieldDef::HasDefault(). |
| 38 |
bool upb_FieldDef_HasDefault(const upb_FieldDef* f); |
| 39 |
``` |
| 40 |
|
| 41 |
For multi-word namespaces, we use `PascalCase`: |
| 42 |
|
| 43 |
```c++ |
| 44 |
// `PyUpb` is the namespace. |
| 45 |
PyObject* PyUpb_CMessage_GetAttr(PyObject* _self, PyObject* attr); |
| 46 |
``` |
| 47 |
|
| 48 |
### Private Functions and Members |
| 49 |
|
| 50 |
Since we do not have `private` in C++, we use a leading underscore convention |
| 51 |
to mark internal functions and variables that should only be accessed from |
| 52 |
upb: |
| 53 |
|
| 54 |
```c++ |
| 55 |
// Internal-only function. |
| 56 |
int64_t _upb_Int64_FromLL(); |
| 57 |
|
| 58 |
// Internal-only members. Underscore prefixes are only necessary when the |
| 59 |
// structure is defined in a header file. |
| 60 |
typedef struct { |
| 61 |
const int32_t* _values; // List of values <0 or >63 |
| 62 |
uint64_t _mask; // Bits are set for acceptable value 0 <= x < 64 |
| 63 |
int _value_count; |
| 64 |
} upb_MiniTable_Enum; |
| 65 |
``` |