Search code examples
cclion

Multiple C Source Files in CLion


In a CLion project, I have two C-language source files, "main.c" and "list.c".

The source file "main.c" has this:

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

The source file "list.c" has this:

#include <stdio.h>

int printFoo() {
    printf("I want Krabby Patties!\n");
    return 0;
}

Now how do I call printFoo() from the main() function? I know I cannot do an include<list.c> in main.c since that will cause a multiple definitions error.


Solution

  • CLion uses CMake for organizing and building project.

    CMakeLists.txt contains instructions for building.

    Command add_executable(program main.c list.c) creates executable with files main.c and list.c. Add all source files to it. You can add headers, but it isn't necessary.

    Header files contain definitions of functions and other things, source files for realization, but you can merge them.


    main.c

    #include "list.h"
    
    int main() {
        printFoo();
        return 0;
    }
    

    list.h

    #pragma once
    int printFoo();
    

    list.c

    #include "list.h"
    #include <stdio.h>
    
    int printFoo(){
        return printf("I want Krabby Patties!\n");
    }
    

    #pragma once tels compiler to include header file once. If you have more than one include of one file without #pragma once, you'll catch an error.