首页 > 解决方案 > 未定义的符号 str::string 和字符串文字

问题描述

我正在学习 C++ 并坚持似乎是一件超级简单的事情。:-(

这是我的 Person.h

#include <string>

class Person {
private:
    std::string firstName;
    std::string lastName;
    int arbitaryNumber;
public:
    Person(std::string firstName, std::string lastName, int arbitaryNumber);
    std::string getName();
};

我的 CPP 文件是:

#include "Person.h"

Person::Person(std::string firstName, std::string lastName, int arbitaryNumber):
    firstName(firstName), lastName(lastName), arbitaryNumber(arbitaryNumber) {
}

std::string Person::getName() {
    return this->firstName + " " + this->lastName;
}

到目前为止,事情都非常简单。让我们主要使用它。

#include <iostream>
# include "Person.h"


int main(int argc, char **argv) {
    Person p("Nawa", "Man", 100);
    return 0;
}

当我编译/运行我的代码时,我得到了这个错误。

Building in: /Users/nawa/eclipse-workspace-CPP/ExampleMake/build/default
make -f ../../Makefile
g++ -c -O2   -o ExampleMake.o /Users/nawa/eclipse-workspace-CPP/ExampleMake/ExampleMake.cpp
g++ -o ExampleMake ExampleMake.o
Undefined symbols for architecture x86_64:
  "Person::Person(std::__1::basic_string<char, std::__1::char_traits<char>, 
std::__1::allocator<char> >, std::__1::basic_string<char, std::__1::char_traits<char>, 
std::__1::allocator<char> >, int)", referenced from:
      _main in ExampleMake.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make: *** [ExampleMake] Error 1
    Build complete (2 errors, 0 warnings): /Users/nawa/eclipse-workspace-    
CPP/ExampleMake/build/default

构造函数有什么问题?我在 Mac 上使用 Eclipse。

我怀疑它与字符串文字和 str::string 有关,但我不确定。所以,当我在命令行中编译它时,我得到了同样的错误,所以这似乎不是 Eclipse 问题。

请帮忙。谢谢。

标签: c++string

解决方案


g++ -o ExampleMake ExampleMake.o

当您有 2 个 cpp 文件时,您只链接一个文件。


推荐阅读