编译包含字符串的代码时遇到问题

trouble compiling code that includes string

本文关键字:遇到 问题 代码 包含 字符串 编译      更新时间:2023-10-16

我有一段简单的代码在编译时遇到问题。

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char **argv) {
string hello = "Hello World";
printf("%sn",hello.c_str());
return 0;
}

使用 "GCC 测试.cpp -O 测试"编译 返回以下消息。

/tmp/ccgbRaOf.o: 在函数main': test.cpp:(.text+0x27): undefined reference tostd::allocator::allocator()' test.cpp:(.text+0x3e):对std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&)' test.cpp:(.text+0x4a): undefined reference tostd::allocator::~allocator()' 的未定义引用 test.cpp:(.text+0x56):未定义对std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::c_str() const' test.cpp:(.text+0x6a): undefined reference tostd::__cxx11::basic_string、std::分配器>::~basic_string()' test.cpp:(.text+0x8f):未定义对std::allocator<char>::~allocator()' test.cpp:(.text+0xa9): undefined reference tostd::__cxx11::basic_string、std:::分配器>::~basic_string()' 的引用/tmp/ccgbRaOf.o: In function__static_initialization_and_destruction_0(int, int)': test.cpp:(.text+0xe9): undefined reference tostd::ios_base::Init::Init()' test.cpp:(.text+0xfe):未定义对std::ios_base::Init::~Init()' /tmp/ccgbRaOf.o:(.data.rel.local.DW.ref.__gxx_personality_v0[DW.ref.__gxx_personality_v0]+0x0): undefined reference to__gxx_personality_v0的引用 collect2:错误:ld 返回 1 个退出状态

我做错了什么?

你用gcc编译它,这是针对 C 的,但你的代码是C++的。使用g++.

它不起作用,因为您使用的是 C 编译器。对于C++,您需要一个不同的编译器。尝试使用g++