Coding Standards for pure C (not C++)

前端 未结 11 1962
盖世英雄少女心
盖世英雄少女心 2020-12-12 14:17

I come from a java background (from my CS classes) and a semester of C++. I am just finishing up a OpenCV project for my Co-Op that\'s in pure C, so I\'m a bit late in aski

11条回答
  •  南笙
    南笙 (楼主)
    2020-12-12 14:52

    You can do object oriented design in pure C. An easy approach is to think of a module as a class with public methods as ordinary functions that require the this parameter as an explicit first argument.

    It helps if the class name is a prefix on the function name, and if all private functions and class data are declared static. You build constructors with malloc() to get the memory, and explicit initialization of the data fields.

    A constructor for an object with entirely private data members can expose an opaque pointer (typed void * even, or as a pointer to an incomplete type if type safety is desired). If you want to have only public data members, then a pointer to a publicly defined struct works well.

    This pattern is followed by a number of libraries. An initialization function returns a cookie that must be passed back to all library methods, and one method serves as a destructor.

    Of course, there are other ways to design well in pure C, but if OO works for you, you don't have to abandon it completely.

提交回复
热议问题