c语言如何调用其他文件中的函数,干货无水,通俗易懂

一共是5个文件:a.h、a.c、和 b.h、b.c 和main.c
先上代码,末尾有解释
a.h

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

解释:调用的时候引入对方的头文件

第一种i方法:编译的时候,要把所有.c文件都加入编译(GCC)

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

第二种方法:编写CMakeLists.txt文件(CMake)

编写CMakeLists.txt

cmake_minimum_required(VERSION 3.23)
project(ctest C)

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

在项目根目录中创建一个build目录。

进入build目录并运行以下命令:

cmake ..

这将生成Makefile或其他构建系统所需的文件。

运行构建命令:

make

或者,如果您使用的是Visual Studio,可以使用以下命令:

cmake --build . --config Release

这将编译源文件并将它们链接成一个可执行文件。

猜你喜欢

转载自blog.csdn.net/qq_46110497/article/details/130471113
今日推荐