gpt4 book ai didi

c++ - 如何从多个cpp文件中调用函数

转载 作者:行者123 更新时间:2023-11-30 03:23:24 24 4
gpt4 key购买 nike

如何在多个 cpp 文件中包含和使用函数?

// my_function.h
void func_i_want_to_include();

// my_function.cpp
void func_i_want_to_include()
{
puts("hello world");
}


//main.cpp
#include "my_function.h"
#include "file_b.h"

int main()
{
call_to_file_b();
func_i_want_to_include();
return 0;
}

//file_b.h
void call_to_file_b();

//file_b.cpp
#include "my_function.h"

void call_to_file_b()
{
puts("from file b\n");
func_i_want_to_include();
}

当我这样做时,链接器“unresolve external symbol”得到 yield,我猜链接器过去 func_i_want_to_include() 2 次而不是理解这是同一个函数。

我怎么告诉他'这是同一个函数,只是从 2 个文件中调用它,但不要尝试制作同一个函数的 2 个拷贝?

最佳答案

首先,正如@LuisGP 提到的,如果您的头文件被多次包含,您需要#ifndef。其次,在关联的cpp文件中,需要包含头文件。头文件声明函数,cpp文件描述函数。最后,编译时必须包含所有 cpp 文件(如果编辑器不起作用,只需使用命令行)。它是这样的:

gcc -c my_function.cpp file_b.cpp //this will make a my_function.o and a file_b.o file
gcc -o main main.cpp my_function.o file_b.o

或简称:

gcc -o main main.cpp my_function.cpp file_b.cpp

文件应该如何写:

// my_function.h
#ifndef _my_function_h
#define _my_function_h

void func_i_want_to_include();

#endif


// my_function.cpp
#include <stdio.h>
#include "my_function.h"

void func_i_want_to_include()
{
puts("hello world");
}


//file_b.h
#ifndef _file_b_h
#define _file_b_h

void call_to_file_b();

#endif


//file_b.cpp
#include <stdio.h>
#include "my_function.h"
#include "file_b.h"

void call_to_file_b()
{
puts("from file b\n");
func_i_want_to_include();
}


//main.cpp
#include "my_function.h"
#include "file_b.h"

int main()
{
call_to_file_b();
func_i_want_to_include();
return 0;
}

第一次回答问题,如有错误,请告诉我,我会改正。希望对您有所帮助。

关于c++ - 如何从多个cpp文件中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50393626/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com