[英]How to call function from multiple cpp files
如何在多个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”获得了收益,我猜链接器经过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;
}
这是我第一次回答问题,如果我有任何错误,请告诉我,我会解决。 希望能帮助到你。
如果要将函数定义放在头文件中,则需要使函数内联。
// my_function.h
inline void func_i_want_to_include()
{
puts("hello world");
}
否则,编译器将为包含头文件的每个cpp文件创建一个函数,链接器将不知道选择哪个函数。
这就是为什么您通常分隔函数声明的原因
void func_i_want_to_include();
从函数定义
void func_i_want_to_include()
{
puts("hello world");
}
前者进入头文件,而后者进入源文件。
正如eozd所说,头文件用于声明。 但是您的问题是头文件被多次包含,每个#include子句包含一次。 您可以解决添加
#pragma once
在标题的顶部或旧的方式:
#ifndef _MY_HEADER_FILE_H_
#define _MY_HEADER_FILE_H_
// Stuff
#endif // _MY_HEADER_FILE_H_
您必须创建一个头文件。 在该文件内创建一个对象,并在类内部实现一个公共函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.