How to call functions in other files in C language, simple and easy to understand

There are a total of 5 files: ah, ac, and bh, bc and main.c.
The code is explained first, and there is an explanation
of ah at the end.

// a.h
#ifndef A_H
#define A_H

int a();

#endif /* A_H */

a.c

// a.c

#include "stdio.h"
int a() {
    
    
    printf("这是a函数 \n");
    return 1;
}

b.h

// b.h
#ifndef B_H
#define B_H

int b();

#endif /* B_H */

b.c

// b.c

#include "a.h"
#include "stdio.h"

int b() {
    
    
    printf("这是b函数 \n");
    a();
    return 1;
}

main.c

// main.c
#include <stdio.h>
#include "b.h"

int main(void) {
    
    
    int a = b();
    printf("%d",a);
    return 1;
}

Explanation: Introduce the header file of the other party when calling

The first i method: When compiling, all .c files must be added to the compilation (GCC)

gcc main.c a.c b.c -o aaa

Second method: Write CMakeLists.txt file (CMake)

Writing CMakeLists.txt

cmake_minimum_required(VERSION 3.23)
project(ctest C)

# 添加可执行文件 ctest是项目名称
add_executable(ctest 
        main.c
        b.c
        a.c)

Create a build directory in the project root directory.

Go into the build directory and run the following commands:

cmake ..

This will generate a Makefile or other files required by the build system.

Run the build command:

make

Alternatively, if you are using Visual Studio, you can use the following command:

cmake --build . --config Release

This will compile the source files and link them into an executable file.

Guess you like

Origin blog.csdn.net/qq_46110497/article/details/130471113