CodeRunner——不能编译多个源c++程序

CodeRunner-- cannot compile multiple source c++ program

本文关键字:c++ 程序 不能 编译 CodeRunner      更新时间:2023-10-16

我对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;
}

我喜欢coderrunner,但这真的让我很沮丧。

谢谢!

对于任何有类似问题的人我已经找到了解决方案:

我错误地使头文件中的类的头文件和实现文件在名称上不同。

header.h应该叫 foobar.h

implementation.cpp应该命名为foobar.cpp

当我将文件名称改为foobar.h和foobar.cpp时,程序在coderrunner中编译并运行良好。

我的教授告诉我,一个类的头文件和它的实现文件应该有相同的名字,不同的文件类型,即x.p和x.h。