簡體   English   中英

如何在另一個 .cpp 文件中使用函數?

[英]How can I use functions in another .cpp file?

我正在 Visual Studio 2013 Preview 中創建一個項目,其中包含我正在學習 C++ 的教程中的代碼。 項目中的主文件包含一個程序,該程序能夠啟動同一項目中另一個 .cpp 文件中定義的功能。 它的代碼如下:

#include "stdafx.h"
#include <iostream>
#include "Comments.cpp"
#include "Structure of a Program.cpp"

int structure(void);
void comment(void);

int main()
{
    using namespace std;
    cout << "This project contains files related to Chapter 1 of Learn CPP
        Tutorials\n" << endl;
    cout << "Please type in the tutorial number to view its output:\n" << 
        "1 - Structure of a Program\n" <<
        "2 - Comments\n" <<
         "3 - A First Look at Variables (and cin)\n" <<
        "4 - A First Look at Functions\n" <<
        "5 - A First Look at Operators\n" <<
        "6 - Whitespace & Basic Formatting\n" <<
        "7 - Forward Declarations\n" <<
                "8 - Programs With Multiple Files\n" <<
        "9 - Header Files\n" <<
        "10 - A First Look at the Preprocessor\n" <<
        "11 - How to Design your First Programs\n" << endl;
    int x;
    cin >> x;
    if (x == 1)
    {
        structure();
    }
    if (x == 2)
    {
         comment();
    }
    cout << "Thank you for using this program. Good bye." << endl;
    return 0;
}

我遇到的問題是,當我構建程序時,總是有一個錯誤說我正在啟動的功能已經定義,即使它們不是這樣。 基本上,我需要有關如何啟動位於不同 .cpp 文件但位於同一項目中的功能的幫助。

謝謝

永遠不要包含 .cpp 文件!

通常,包含 .cpp 文件將導致重新編譯不應或可能不會多次編譯的代碼(因此會出現鏈接錯誤)。 另一方面,在 .h 文件中,您將聲明和其他可能編譯多次的內容放入,對於該 .h 文件的每個包含,它們將大致編譯一次。

在這種情況下,由於您已經聲明了 structure() 和 comment(),您可能不需要用任何東西替換 .cpp 包含。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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