C-specific syntax sugar (C99+)
Macros + inline + GCC/Clang extensions let EtherCAT SDK client code be written compactly and readably.
The DarraEtherCAT C SDK provides 7 standalone helper headers under internal/sugar/. All of them are pure inline + macro: no extra link symbols, no runtime cost.
The sugar headers ship in the internal/ directory of the source package/installer (after installation they live at <prefix>/share/darra-ethercat/internal/sugar/); they are not public headers under include/. Add internal/ to the include path before use and the #include "sugar/..." lines in the examples below work as written. Not using sugar at all has no effect on the standard API.
You can include the umbrella header directly:
#include "ethercat.h"
#include "sugar/sugar.h"
Or pick individual ones as needed:
#include "sugar/foreach.h"
#include "sugar/try_macro.h"
| Sub-header | Topic | C standard requirement |
|---|---|---|
sugar/foreach.h | Iteration macros | C99 |
sugar/try_macro.h | Error handling macros | C89 |
sugar/inline_getters.h | Short-name inline wrappers | C99 |
sugar/cleanup.h | RAII-style automatic cleanup | GCC / Clang (EC_WITH_* works on any compiler) |
sugar/designated_init.h | Recommended configuration presets / compound literal | C99 |
sugar/token_paste.h | Batch declarations / enum name mapping | C89 |
sugar/generic.h | C11 _Generic type dispatch | C11 |
The sections below follow the files, giving semantics, API lists and typical examples.
Designated struct initializers and compound literals — sugar/designated_init.h
Use designated initializers directly
ec_startup_param_t sp = {
.index = 0x6060,
.sub_index = 0,
.data = { 8 },
.data_len = 1,
.transition = EC_TRANS_PS,
.timing = EC_TIMING_BEFORE,
.priority = 100,
.complete_access = 0,
.is_register_write= 0,
};
Unspecified fields are zero-initialized automatically. Adding a new field does not break old code.
Recommended configuration presets
designated_init.h provides 4 common cycle presets that can be used directly as initial values:
ec_cycle_preset_t cfg = EC_PRESET_CYCLE_1MS;
cfg.cpu = 5; // local override
EC_PRESET_CYCLE_4MS— cycle 4 ms, CPU 0, priority 10, DC no, real-time mode noEC_PRESET_CYCLE_1MS— cycle 1 ms, CPU 3, priority 50, DC yes, real-time mode yesEC_PRESET_CYCLE_500US— cycle 500 µs, CPU 5, priority 80, DC yes, real-time mode yesEC_PRESET_CYCLE_250US— cycle 250 µs, CPU 7, priority 99, DC yes, real-time mode yes
Each preset also has a _AS_LITERAL compound literal version that can be passed to a function as a temporary value and taken by address with &:
apply_cycle(&EC_PRESET_CYCLE_500US_AS_LITERAL);
Shorthand macro EC_CYCLE(...)
apply_cycle(EC_CYCLE(.cycle_ns = 1000000, .cpu = 3, .use_dc = 1));
It expands to ((ec_cycle_preset_t){ .cycle_ns = 1000000, .cpu = 3, .use_dc = 1 }), a standard C99 compound literal. No variable declaration is needed; one line does it.
SDO startup parameter shorthand
ec_startup_param_t sp = EC_SDO_DOWNLOAD_SHORT(0x6060, 0, 8, /*priority*/100);
AddStartupParameter(mi, si, &sp);
AddStartupParameter(master_index, slave_index, const ec_startup_param_t*) adds the entry to the slave's startup parameter pipeline, and the master sends it automatically on state transitions; the companion interfaces are AddStartupParameterBatch / ClearStartupParameters / GetStartupParameterCount / ApplyStartupParameters. The macro splits the 32-bit value into 4 little-endian bytes and sets EC_TRANS_PS + EC_TIMING_BEFORE. It suits repetitive boilerplate such as "send the mode word before PreOp" in bulk.
Iteration macros — sugar/foreach.h
C has no foreach, but macros make it read naturally.
Basic: EC_FOREACH_SLAVE
EC_FOREACH_SLAVE(mi, si) {
printf("[%u] vid=0x%08X pid=0x%08X\n",
si, GetSlaveVendorId(mi, si), GetSlaveProductCode(mi, si));
}
The macro declares its own loop variable and caches the upper bound internally:
for (uint16_t si = 1, _ec_n_si = ec_foreach_slave_count_(mi);
si <= _ec_n_si; ++si) { ... }
ec_foreach_slave_count_(mi) is called only once at the start of the loop (it reads slavecount through GetMasterState), so it does not hit the SDK on every iteration.
Iterate by group: EC_FOREACH_SLAVE_IN_GROUP
EC_FOREACH_SLAVE_IN_GROUP(mi, si, /*group=*/2) {
/* To write outputs use WriteSlaveOutputPdo, see PDO inputs and outputs */
}
Only slaves with GetSlaveGroup(mi, si) == 2 enter the loop body. Internally it filters with if (条件不满足) continue; else (the continue form produces no dangling else binding and does not rewrite the loop structure), and break still exits normally.
OP state only: EC_FOREACH_OP_SLAVE
EC_FOREACH_OP_SLAVE(mi, si) {
/* Only slaves whose base state is OPERATIONAL enter the loop */
}
Before testing, the AL error bits are stripped (compared after & 0x0F), so 0x18 (OP|ERROR) also enters the loop; to iterate only slaves carrying the error bit, use EC_FOREACH_ERROR_SLAVE.
Topology iteration
ec_topology_node_t nodes[64];
uint16_t roots[8];
TopologyBuild(mi, nodes, 64);
int nroot = TopologyGetRoots(mi, roots, 8);
EC_FOREACH_ROOT(roots, nroot, ri) {
uint16_t children[16];
int nc = TopologyGetChildren(mi, roots[ri], children, 16);
EC_FOREACH_CHILD(children, nc, ci) {
// children[ci] is the child slave index
}
}
Note: filter macros such as EC_FOREACH_SLAVE_IN_GROUP / EC_FOREACH_OP_SLAVE filter with continue and attach the loop body to a trailing else, so a multi-statement loop body must use explicit braces, otherwise it binds to the internal continue / else. Do not wrap these two macros in a bare if without braces at the outer level either.
Error handling macros — sugar/try_macro.h
C has no exceptions; the "goto fail and clean up in one place" pattern common in industrial SDK code fits in one line.
EC_OK / EC_ERR naming
if (SetState(mi, EC_STATE_OPERATIONAL) == EC_OK) { ... }
EC_OK is defined as 1 (matching BOOL TRUE) and EC_ERR as 0. This makes BOOL-returning SDK functions read more like a state machine.
EC_TRY(expr) — goto fail on failure
int do_init(const char* nic) {
uint16_t mi = 0;
mi = Initialize();
EC_TRY(mi != 0); // on failure jump to fail
EC_TRY(SetNetwork(mi, nic, "") != 0);
EC_TRY(SetStateSequence(mi, EC_STATE_OPERATIONAL, 5000));
Start(mi);
return 0;
fail:
if (mi) Dispose(mi);
return -1;
}
The fail: label must exist, otherwise GCC reports label 'fail' used but not defined. That constraint effectively forces the engineer to write the cleanup path.
EC_TRY_LOG(expr, msg) — log on failure
EC_TRY_LOG(SetState(mi, EC_STATE_OPERATIONAL),
"SetState OPERATIONAL 失败"); /* SetState OPERATIONAL failed */
The default implementation uses fprintf(stderr, ...). If the project has its own logging system, define the hook before #include "sugar/try_macro.h":
#define EC_TRY_LOG_HOOK(msg) my_logger("ec", msg)
#include "sugar/try_macro.h"
EC_RETURN_IF_FAIL(expr, retval)
Suited to small functions that need no cleanup:
int read_voltage(uint16_t mi, uint16_t si, uint32_t* out) {
EC_RETURN_IF_FAIL(out != NULL, -1);
EC_RETURN_IF_FAIL(ec_slave_count(mi) >= si, -2);
*out = GetSlaveVendorId(mi, si);
return 0;
}
EC_GOTO_IF_FAIL(expr, label) — multi-level cleanup
EC_GOTO_IF_FAIL(SetNetwork(mi, ...), cleanup_dispose);
EC_GOTO_IF_FAIL(SetStateSequence(...), cleanup_stop);
Start(mi);
return 0;
cleanup_stop: Stop(mi);
cleanup_dispose: Dispose(mi);
return -1;
EC_BREAK_IF_FAIL(expr) / EC_ASSERT_RANGE(v, lo, hi)
EC_BREAK_IF_FAIL does break on failure inside a loop. EC_ASSERT_RANGE does return -1 when out of range (not EC_ERR — this SDK's int-return convention is 0 = success, so returning EC_ERR (0) from an int function would falsely report success), which is safer than assert() (it is not removed in release builds).
Short-name inline wrappers — sugar/inline_getters.h
The main SDK uses PascalCase function names (GetSlaveVendorId and so on). This header adds a set of short ec_* names that only forward directly; the compiler inlines them away completely.
| Short name | Category | Access | Equivalent main API | Return type |
|---|---|---|---|---|
ec_slave_count(mi) | Master state | Read-only | GetMasterState() reads slavecount | uint16_t |
ec_link(mi) | Link | Read-only | (ec_link_state_t)GetLinkStatus(mi) | ec_link_state_t |
ec_vendor(mi, si) | Slave identity | Read-only | GetSlaveVendorId(mi, si) | uint32_t |
ec_product(mi, si) | Slave identity | Read-only | GetSlaveProductCode(mi, si) | uint32_t |
ec_revision(mi, si) | Slave identity | Read-only | GetSlaveRevision(mi, si) | uint32_t |
ec_serial(mi, si) | Slave identity | Read-only | GetSlaveSerialNumber(mi, si) | uint32_t |
ec_addr(mi, si) | Slave identity | Read-only | GetSlaveConfigAddr(mi, si) | uint16_t |
ec_alias(mi, si) | Slave identity | Read-only | GetSlaveAliasAddr(mi, si) | uint16_t |
ec_state(mi, si) | Slave state | Read-only | (ec_state_t)GetSlaveState(mi, si) | ec_state_t |
ec_alstatus(mi, si) | Slave state | Read-only | GetSlaveALStatusCode(mi, si) | uint16_t |
ec_is_op(mi, si) | Slave state | Read-only | Compares against EC_STATE_OPERATIONAL | int (1/0) |
ec_has_error(mi, si) | Slave state | Read-only | Checks the EC_STATE_ERROR bit | int (1/0) |
ec_out_bytes(mi, si) | Process data | Read-only | GetSlaveOutputBytes(mi, si) | uint32_t |
ec_in_bytes(mi, si) | Process data | Read-only | GetSlaveInputBytes(mi, si) | uint32_t |
ec_parent(mi, si) | Topology | Read-only | GetSlaveParent(mi, si) | uint16_t |
There are also two debug logging helpers:
ec_state_t s = ec_state(mi, si);
printf("slave[%u] state=%s alstatus=0x%04X\n",
si, ec_state_name(s), ec_alstatus(mi, si));
printf("link=%s\n", ec_link_name(ec_link(mi)));
ec_state_name returns "INIT" / "PRE_OP" / "BOOT" / "SAFE_OP" / "OP" / "NONE" and "UNKNOWN" for any other value; it masks the error bits (& 0x0F) before deciding.
Cleanup attribute (GCC / Clang) — sugar/cleanup.h
GCC and Clang support __attribute__((cleanup(fn))), which calls fn(&var) automatically when the variable leaves scope. This makes RAII-style C possible.
EC_AUTO_DISPOSE
void demo(const char* nic) {
EC_AUTO_DISPOSE uint16_t mi = Initialize();
if (!mi) return;
SetNetwork(mi, nic, "");
SetStateSequence(mi, EC_STATE_OPERATIONAL, 5000);
Start(mi);
// Dispose(mi) runs automatically when the function returns. return / goto also trigger it.
}
EC_AUTO_STOP_DISPOSE
Suits resources acquired after Start(): Stop runs first and then Dispose on exit:
EC_AUTO_STOP_DISPOSE uint16_t mi = Initialize();
SetNetwork(mi, "eth0", "");
Start(mi);
// on leaving scope: Stop(mi); Dispose(mi);
EC_AUTO_FREE / EC_AUTO_FREE_SDK
EC_AUTO_FREE void* user_buf = malloc(4096); // free()
EC_AUTO_FREE_SDK void* sdk_buf = SomeSdkAlloc(); // FreeMemory() (allocated inside the SDK)
Alternative for all compilers: EC_WITH_* / EC_CLEANUP_* (recommended)
When the cleanup attribute is unavailable (MSVC / strict C89), use the for-loop guard or the manual cleanup primitives; semantics match EC_AUTO_*:
EC_WITH_DISPOSE(mi) { ... } // Dispose(mi) at the end of the block
EC_WITH_STOP_DISPOSE(mi) { ... } // Stop(mi) + Dispose(mi) at the end of the block
EC_WITH_FREE(ptr) { ... } // free(ptr) at the end of the block
EC_WITH_FREE_SDK(ptr) { ... } // FreeMemory(ptr) at the end of the block
EC_CLEANUP_DISPOSE(mi) / EC_CLEANUP_STOP_DISPOSE(mi) / EC_CLEANUP_FREE(ptr) / EC_CLEANUP_FREE_SDK(ptr) are explicit-call versions with the same semantics, triggering cleanup manually at any point.
MSVC notes
MSVC does not support the cleanup attribute. On non-GCC/Clang compilers the header does not define EC_AUTO_* (using them is a compile error, not a silent no-op), so use EC_WITH_* / EC_CLEANUP_* above, or clean up manually. Cross-platform code can test with the preprocessor:
#if EC_HAS_CLEANUP_ATTR
EC_AUTO_DISPOSE uint16_t mi = Initialize();
#else
uint16_t mi = Initialize();
/* ... manual Dispose */
#endif
Token paste batch declarations — sugar/token_paste.h
The C preprocessor's ## operator concatenates tokens at compile time, which suits generating boilerplate in batches.
EC_DECLARE_GETTER(name, type, fn) — batch-declare typed getters
EC_DECLARE_GETTER(slave_vendor, uint32_t, GetSlaveVendorId)
EC_DECLARE_GETTER(slave_product, uint32_t, GetSlaveProductCode)
EC_DECLARE_GETTER(slave_state, uint8_t, GetSlaveState)
EC_DECLARE_GETTER(slave_alias, uint16_t, GetSlaveAliasAddr)
After expansion, each declaration produces an inline:
static inline uint32_t ec_get_slave_vendor(uint16_t mi, uint16_t si) {
return GetSlaveVendorId(mi, si);
}
EC_DECLARE_GETTER1(name, type, fn) is the single-argument version (master index).
EC_BEGIN_NAME_MAP / EC_NAME_MAP_ENTRY / EC_END_NAME_MAP
A lookup function from enum to string:
EC_BEGIN_NAME_MAP(my_state, ec_state_t)
EC_NAME_MAP_ENTRY(EC_STATE_INIT, "INIT")
EC_NAME_MAP_ENTRY(EC_STATE_PRE_OP, "PRE_OP")
EC_NAME_MAP_ENTRY(EC_STATE_SAFE_OP, "SAFE_OP")
EC_NAME_MAP_ENTRY(EC_STATE_OPERATIONAL, "OP")
EC_END_NAME_MAP("UNKNOWN")
The generated function static inline const char* my_state_name(ec_state_t v); can be called directly. Limitation: only suitable for small enums (< 64 entries).
Utility macros
EC_STRINGIFY(x)— token to string literal (double indirection, so macros expand)EC_LOC—__FILE__ ":" __LINE__string, useful for loggingEC_CONCAT(a, b)/EC_CONCAT3(a, b, c)— concatenate tokens (expands macros)EC_ARRAY_LEN(arr)— static array length,(int)(sizeof(arr)/sizeof((arr)[0]))EC_UNUSED(x)—(void)(x), suppresses unused-variable warnings
C11 _Generic type dispatch — sugar/generic.h
Works only with C11+ compilers. In C99 mode every macro degrades to a compatible version.
ec_byte_size(x) — type byte width
uint32_t a; int8_t b; double c;
printf("%d %d %d\n", ec_byte_size(a), ec_byte_size(b), ec_byte_size(c));
// output: 4 1 8
In C99 it degrades to (int)sizeof(x). Integer and floating-point types in the table behave the same on both sides; other types (pointers, structs) fall to default: 0 in the C11 _Generic branch, which does not match the sizeof fallback — do not use it to measure the width of a non-scalar.
ec_print_value(label, v) — type-safe printing
uint32_t vendor = ec_vendor(mi, 1);
ec_print_value("vendor", vendor);
// output: vendor = 305419896
Internally the macro uses _Generic plus format macros from <inttypes.h> such as PRId32, so no hand-written %u/%lu/%hd is needed. In C99 it degrades to ((void)0); the caller uses printf directly.
ec_max(a, b) / ec_min(a, b)
Minimal macros built on the ternary operator. Note that they evaluate their arguments twice, so do not pass expressions with side effects.
Opaque handle pattern
The DarraEtherCAT C SDK uses a uint16_t master index as an opaque handle: what the user holds is not a struct pointer but a numeric index (the parameter name in each API is master_index / mi). This pattern needs no sugar header, but is worth stating in the docs:
uint16_t mi = Initialize(); // opaque handle
SetNetwork(mi, "eth0", ""); // every API takes mi
/* ... */
Dispose(mi);
Benefits:
- Does not expose internal struct layout; the ABI stays stable (new fields do not break SDK clients)
- Safe to pass values across process / DLL boundaries (an integer, not a pointer)
- Also supports multiple instances (
InitializeSpecificMaster(N))
master_index = 0 always means "invalid" / uninitialized. Most SDK APIs explicitly check master_index != 0.
Complete example
Pulling all the sugar above together, a complete PreOp → SafeOp → OP startup sequence:
#include "ethercat.h"
#include "sugar/sugar.h"
#include <stdio.h>
int main(int argc, char** argv) {
if (argc < 2) {
fprintf(stderr, "usage: %s <nic>\n", argv[0]);
return 1;
}
/* C99 designated initialization */
ec_cycle_preset_t cfg = EC_PRESET_CYCLE_1MS;
cfg.cpu = 5;
/* automatic Dispose (GCC/Clang); manual Dispose is required under MSVC */
EC_AUTO_DISPOSE uint16_t mi = Initialize();
EC_RETURN_IF_FAIL(mi != 0, 2);
/* try-fail pattern */
EC_TRY_LOG(SetNetwork(mi, argv[1], "") != 0,
"SetNetwork 失败, 检查 NIC 名称"); /* SetNetwork failed, check the NIC name */
EC_TRY_LOG(SetStateSequence(mi, EC_STATE_OPERATIONAL, 5000),
"状态序列未达到 OP"); /* The state sequence did not reach OP */
/* start the RT cycle */
Start(mi);
/* short names + iteration + state strings */
printf("link=%s, slaves=%u\n",
ec_link_name(ec_link(mi)), ec_slave_count(mi));
EC_FOREACH_OP_SLAVE(mi, si) {
printf(" [%u] vid=0x%08X pid=0x%08X state=%s\n",
si, ec_vendor(mi, si), ec_product(mi, si),
ec_state_name(ec_state(mi, si)));
}
/* cleanup — Stop is called explicitly, Dispose is handled by EC_AUTO_DISPOSE */
Stop(mi);
return 0;
fail:
/* EC_TRY_LOG jumps here on failure */
return 3;
}
FAQ
Q: Does sugar slow down the runtime?
A: No. Every inline function is marked static inline, so the compiler eliminates the call completely. Macros expand in the preprocessing stage, with 0 runtime cost.
Q: Can I skip sugar? A: Yes, entirely. The main SDK API is decoupled from the sugar headers and pulls in no sugar dependency. Sugar is only a more compact way of writing things for engineers who want it.
Q: My project uses C89. Which sugar is available? A:
- Error handling (
try_macro.h) — all macros work; the failure-site inline in the same header needs C99 / gnu extensions under GCC (MSVC__inlineworks) - Iteration (
foreach.h) — unavailable (relies on C99 block-scope multi-variable declarations such asfor (uint16_t si = 1, ...)) - inline wrappers (
inline_getters.h) —__inlineworks on MSVC; GCCstatic inlineneeds C99 - cleanup — unrelated to the C standard; it depends on whether the compiler supports it; when it does not, use
EC_WITH_*/EC_CLEANUP_* - designated initialization — needs C99
- token paste — works on C89
- _Generic — needs C11
Q: Can an MSVC project use cleanup?
A: Not EC_AUTO_*. MSVC does not implement the GCC cleanup attribute, and the header does not define EC_AUTO_* under MSVC (using them is a direct compile error). Use the all-compiler EC_WITH_DISPOSE / EC_CLEANUP_DISPOSE and friends instead, or call Dispose / Stop / free manually.
Q: Does this sugar affect the ABI? A: No. Everything is macros + inline inside header files; no new symbols are exported and the binary layout of the main SDK is unchanged.
File overview
internal/sugar/
├── sugar.h — umbrella header (includes everything below)
├── foreach.h — iteration macros
├── try_macro.h — error handling + EC_OK/EC_ERR
├── inline_getters.h — short-name inline wrappers
├── cleanup.h — GCC/Clang automatic cleanup
├── designated_init.h — recommended configuration presets + compound literal
├── token_paste.h — batch declarations + name mapping
└── generic.h — C11 _Generic