簡體   English   中英

如何從多個cpp文件調用函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM