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

前端 未结 6 1864

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 14:03

    Just to give you an idea.

    create a file called print.c, put this inside:

    #include 
    #include 
    #include 
    
    void print_on_stdout(const char *msg) {
       if (msg) fprintf(stdout, "%s\n", msg);
    }
    void print_on_stderr(const char *msg) {
       if (msg) fprintf(stderr, "%s\n", msg);
    }
    

    create a file called print.h, put this inside:

    void print_on_stdout(const char *msg);
    void print_on_stderr(const char *msg);
    

    create a file called main.c, put this inside:

    #include 
    #include 
    #include 
    
    #include "print.h"
    
    int main() {
        print_on_stdout("test on stdout");
        print_on_stderr("test on stderr");
    
        return 0;
    }
    

    Now, for each C file, compile with:

    gcc -Wall -O2 -o print.o -c print.c
    gcc -Wall -O2 -o main.o -c main.c
    

    Then link compiled files to generate an executable:

    gcc -Wall -O2 -o test print.o main.o
    

    Run ./test and enjoy.

提交回复
热议问题