C Programming Guide Question: How to track error codes?

  • I have a project in visual studio that contain more than 10 header and source files. I start to realize I did not assign return error codes for each header correctly (i.e I found out that there are multiple error codes with the same value in different headers with different names, some error values even match state values like the function’s return has the value with error value even though I intended to use that value for a correct case return).

  • Can anyone suggest suggest how to track these #define values properly? Should I add them all in a single file?


There are three possible approaches. The first is to use errno.h and strerror(). This is obviously easiest if you can get away with it. But it sounds like you need your own specific error codes.

One way to define your own errors is to have a single error domain for your entire project, in which case you have a central header file that lists all the error codes and a common strerror()-like function to translate into something the user will understand.

The other approach is to have each of your modules have their own error domain, define their own error codes, and provide their own version of strerror(). That’s more work, but gives you the most flexibility.

Usually I find the common error domain more convenient because, in most projects, routines in one module call routines in another module, and you’d like them to return a single error code that has a unique meaning no matter where it came from.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *