Faris Durrani
Faris Durrani

Reputation: 37

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.

Upvotes: 0

Views: 2666

Answers (2)

Wootiae
Wootiae

Reputation: 848

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.

Upvotes: 1

Hitokiri
Hitokiri

Reputation: 3689

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;
}

Upvotes: 0

Related Questions