How can I split up my monolithic programs into smaller, separate files?

前端 未结 6 1806

In all the code I see online, programs are always broken up into many smaller files. For all of my projects for school though, I\'ve gotten by by just having one gigantic C sour

6条回答
  •  臣服心动
    2021-02-20 13:38

    Well, that's exactly what you want : split your code in several libraries !

    Let's take an example, in one file you have :

    #include 
    
    int something() {
        return 42;
    }
    
    int bar() {
        return something();
    }
    
    void foo(int i) {
        printf("do something with %d\n", i);
    }
    
    int main() {
        foo(bar());
        return 0;
    }
    

    you can split this up to :

    mylib.h:

    #ifndef __MYLIB_H__
    #define __MYLIB_H__
    
    #include 
    
    int bar();
    void foo();
    
    #endif
    

    N.B.: the preprocessor code above is called a "guard" which is used to not run twice this header file, so you can call the same include at several places, and have no compilation error

    mylib.c:

    #include 
    
    int something() {
        return 42;
    }
    
    int bar() {
        return something();
    }
    
    void foo(int i) {
        printf("do something with %d\n", i);
    }
    

    myprog.c:

    #include 
    int main() {
        foo(bar());
        return 0;
    }
    

    to compile it you do :

    gcc -c mylib.c -I./
    gcc -o myprog myprog.c -I./ mylib.o
    

    now the advantages ?

    1. it enables you to split logically your code, and then find the code unit faster
    2. it enables you to split your compilation, and recompile only what you need when you modified something (which is what the Makefile does for you)
    3. it enables you to expose some functions and hide others (like the "something()" in the example above), and it helps documenting your APIs for people that will read your code (like your teacher) ;)

提交回复
热议问题