链接器错误与我的自定义命名空间

时间:2013-06-03 16:22:45

标签: c++ namespaces linker-errors

我正在尝试使用一些函数创建自定义命名空间。当我编译我的测试文件时,我得到以下链接器错误:

Undefined                       first referenced
 symbol                             in file
Direction_ns::operator<<(std::basic_ostream<char, std::char_traits<char> >&, Direction_ns::Direction) /var/tmp//cc3entPx.o
ld: fatal: symbol referencing errors. No output written to a.out
collect2: error: ld returned 1 exit status

这是我的标题:

#ifndef DIRECTION_H
#define DIRECTION_H
#include <iostream>
#include <stdexcept>
#include <string>

namespace Direction_ns{
  enum Direction { Up, Down, Left, Right };

  extern std::ostream& operator<<(std::ostream&, const Direction);
  extern std::istream& operator>>(std::istream&, Direction&);

  class bad_direction : public std::runtime_error{
  public:
    explicit bad_direction(const std::string& what_arg)
      : runtime_error(what_arg) {}
  };
}
#endif

这是我的来源:

#include <iostream>
#include <string>
#include "Direction.h"

using namespace std;


ostream& Direction_ns::operator<<(ostream& o, const Direction d){
  string s;

  switch (d){
  case 0:
    s = "Up";
    break;
  case 1:
    s = "Down";
    break;
  case 2:
    s = "Left";
    break;
  case 3:
    s = "Right";
    break;
  default:
    throw bad_direction("Out of range");
    break;
  }
  o << s;
  return o;
}

istream& Direction_ns::operator>>(istream& i, Direction & d){
  string str;
  if(!(i >> str))
    return i;
  if(str == "Up")
    d = static_cast<Direction>(0);
  else if(str == "Down")
    d = static_cast<Direction>(1);
  else if(str == "Left")
    d = static_cast<Direction>(2);
  else if(str == "Right")
    d = static_cast<Direction>(3);
  else
    throw bad_direction("Out of range");
  return i;
}

这是测试文件:

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

using namespace std;
using namespace Direction_ns;

int main()
{

   for (Direction d = Up; d <= Right; d = static_cast<Direction>(d + 1))
   {
      cout << d << '\n';
   }

   return 0;
}

2 个答案:

答案 0 :(得分:0)

您可能忘记同时构建Direction.cpptest.cpp

在我的环境中正常运行g++ test.cpp Direction.cpp(gcc版本4.7.2(Debian 4.7.2-5))。

但是,尝试仅构建test.cpp会导致以下错误:

test.cpp:(.text+0x1c): undefined reference to `Direction_ns::operator<<(std::ostream&, Direction_ns::Direction)'`

答案 1 :(得分:0)

标题表示operator<<(std::stream&, const Direction)在名称空间Direction_ns中定义。第一个源文件在全局命名空间中定义为operator<<(std::stream&, const Direction)。命名空间Direction_ns中没有定义。