2016-11-11 181 views
0

我在C++編程和一般編程方面很新穎。最近我們已經在課堂上將頭文件和其他源文件(實現)添加到我們的程序中。我試過編寫最簡單的程序,以確保我理解將多個文件包含到一個程序中的基礎知識,但它們不會編譯,從而導致鏈接器錯誤。CodeRunner--無法編譯多個源代碼的C++程序

即:

Undefined symbols for architecture x86_64: 
    "FooBar::printSomething()", referenced from: 
     _main in main-d52d70.o 
ld: symbol(s) not found for architecture x86_64 
clang: error: linker command failed with exit code 1 (use -v to see invocation) 

當我通過 「g ++ main.cpp中implementation.cpp」 終端編譯,一切工作就好了。

我的代碼:

的main.cpp

#include "header.h" 

int main() 
{ 
    FooBar object; 
    object.printSomething(); 
    return 0; 
} 

header.h

#ifndef _Header_h_ 
#define _Header_h_ 

#include <iostream> 

using namespace std; 

class FooBar{ 
    public: 
     void printSomething(); 

    private: 
     string helloWorld; 
}; 

#endif 

implementation.cpp

#include "header.h" 

void FooBar::printSomething(){ 
    helloWorld = "Hello World!\n"; 
    cout << helloWorld; 
} 

我喜歡CodeRunner,但這真的讓我很沮喪。

謝謝!

+0

您確定您已將'implementation.cpp'添加到叮噹中的待鏈接對象嗎?另外,在Header.h中添加'#include ' –

回答

0

對於有過類似的問題人我已經找到了解決辦法

我錯在製作類的頭文件和實現文件在不同的名頭文件。

header.h應該被命名爲foobar.h中

implementation.cpp應該被命名爲foobar.cpp

,當我修改過的文件的名稱foobar.h中和foobar.cpp程序編譯並在CodeRunner中運行得很好。

我的教授告訴我,一個類的頭文件和它的實現文件應該有不同的文件類型,即x.cpp和x.h。