Code Organization Style for C?

I know some higher-level languages, all web pages (PHP, javascript, some python). I finally decided to learn a lower level language, and I decided to go with C. The problem is that all the languages ​​I use are largely OOP based. Seeing (based on research) C has no classes or inheritance. As a result, I ask you: how should I organize my C code in an organized way, such as OOP, without having to switch languages ​​or just files with an infinite number of functions?

Change from the future . This question looks rather silly back. I was 15 years old and I did not have CS at my school ...

+3
source share
5 answers

C does not offer many ways to organize code. There are functions and files.

Whenever you want to implement an interface with a hidden implementation, or possibly with private functions, create two files, for example, "foo.h" and "foo.c".

The interface and / or public functions are prototypes of functions in "foo.h", and functions are written in "foo.c". In addition, any hidden implementation or other private functions are located in "foo.c", but are marked as static, for example static int foo_internal_function(int i);. Functions marked staticcan only be specified in the file in which they exist, and not in another.

, , Foo_discombobulate_developers(). , . , .

C , . , - ( C, , ) .

+16

" "

, , . . - , , :

foo.h:

int GetFoo();

Foo.c:

int GetFoo()
{
   ...
}

, . , "this", . "-" C. , , . :

bar.h:

typedef int BAR_OBJ

BAR_OBJ MakeBar();

int GetBarSize(BAR_OBJ);

void DoFooToBar(BAR_OBJ, ...)

Bar.c

   struct BarDetails
   {
      int isFree;
      int size;
      ...
      // other info about bar
   };

   static BarDetails arrayOfBars[...]; // 

   BAR_OBJ MakeBar()
   {
       // search BarDetails array, find free Bar    
   }

   int GetBarSize(BAR_OBJ obj)
   {
       return arrayOfBars[obj];
   }

   void DoFooToBar(BAR_OBJ, ...)
   {
      // lookup bar obj and do something
   }
+8

, ++, OO.

C, OO, . , , .

+3

, C, OOP:

MyClass.

/* MyClass.h or myclass.h */

#ifndef MYCLASS_H
#define MYCLASS_H

struct myclass_s;
typedef struct myclass_s myclass_t;

myclass_t * myclass_new();
void delete_myclass(myclass_t *);

    // Method int doMyStuff(int arg1,int arg2)
int myclass_doMyStuff(myclass_t *, int arg1, int arg2);

#endif //MYCLASS_H

myclass_t, myclass_s. , , C, , ++ , . C, ++. .c :

/* MyClass.c or myclass.c */

#include "myclass.h" // Or MyClass.h

struct myclass_s {
   int exampleField;
};

myclass_t * myclass_new()
{
   myclass_t * o=(myclass_t*)malloc(sizeof(myclass_t));
   // Initialize o here.
   return o;
}

void myclass_delete(myclass_t * o)
{
   // Do any cleanup needed on o here.
   free(o);
}

int myclass_doMyStuff(myclass_t * o,int arg1,int arg2)
{
   // ...
}

C, . , , , , . , . , libpng - ( "", setjmp/longjmp, ).

+3

GObject OOP-ish C, /, .

+1

Source: https://habr.com/ru/post/1718577/


All Articles