【问题标题】:C++ linking error upon using "string"使用“字符串”时的 C++ 链接错误
【发布时间】:2013-12-08 07:16:40
【问题描述】:

我正在使用 C++ 开发一个业余爱好迷你项目,运行我的二进制文件时出现以下错误。

Undefined symbols for architecture x86_64:
  "std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >::__init(char const*, unsigned long)", referenced from:
      recv_line(int) in networking.o
ld: symbol(s) not found for architecture x86_64

我有一个文件networking.cpp,它使用了一个“std::string”的实例。我的网络中有以下内容。h

#ifndef _NETWORKING_H
#define _NETWORKING_H

#include <iostream>
#include <string>

#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define DELIMITER '\n'

std::string recv_line(int sockfd);
#endif

在networking.cpp里面我只有:-

std::string recv_line(int sockfd) {
return "";
}

我做错了什么?

[编辑]

我正在制作如下文件:-

% cat Makefile
CXX=g++

blah: main networking
    $(CXX) main.o networking.o -o blah -v
main:
    $(CXX) -c main.cpp
networking:
    $(CXX) -c networking.cpp
% make

g++的版本好像是:-

% g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.0.0
Thread model: posix

【问题讨论】:

  • 你如何编译以及如何链接你的程序?请显示相关命令! g++ 是哪个版本的?
  • 添加了该信息,谢谢
  • 你的Makefile 格式不正确:可能CC 应该经常被$(CC) 替换,你真的应该使用CXX 而不是CC;顺便说一句,将-Wall -g 传递给g++ 非常有用!
  • 我已经添加了,但错误似乎仍然存在
  • 这不是问题,但是以下划线开头后跟大写字母 (_NETWORKING_H) 的名称和包含两个连续下划线的名称保留给实现。不要使用它们。

标签: c++ macos linker g++ clang


【解决方案1】:

您需要将stdc++ 库链接到您的程序。您可以在此处执行此操作。

$(CC) main.o networking.o -o blah -v -lstdc++.

此处的错误表明libstdc++ 没有与您的程序链接。

另外,在 make 文件中,使用 $(CC) 而不是 CC

【讨论】:

  • 正确配置的g++ 应该隐式链接-lstdc++(并且该库取决于编译器)。在 Linux 上,不需要告诉 g++ 关于 -lstdc++ ;顺便说一句,这是 gccg++ 之间的区别之一;两者都能够编译 C++ 文件 *.cpp*.cc 但以不同的方式链接它们!
猜你喜欢
  • 1970-01-01
  • 2013-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多