简体   繁体   中英

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.

You can create one header file "list.h"

#ifndef __LIST_H__
#define __LIST_H__ 

int printFoo();

#endif

Then include it in main.c :

#include <stdio.h>
#include "list.h"

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM