8

这些函数是我的大多数程序对象将使用的实用程序类型的东西。我想将它们放在一个命名空间中并让它们全局化。这个命名空间在头文件中定义,然后添加到我的预编译头文件中。然而到目前为止,我已经在 2 个不同的对象中使用了这个命名空间中的函数,并且编译器在这 2 个对象上抛出了多重定义的符号错误。

命名空间文件

#ifndef UTILS_H
#define UTILS_H

#include <random>
#include <cmath>


namespace Utils
{
    extern int GetRandomBetween(int low, int high)
    {
        if (low < 0 || low >= high)
            return 0;
        int seed = high - low;

        return (rand() % seed) + low;
    }
};

#endif

和我的预压缩头

// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#pragma once

#include "targetver.h"

//#define WIN32_LEAN_AND_MEAN             // Exclude rarely-used stuff from Windows headers
// Windows Header Files:
#include <windows.h>

// C RunTime Header Files
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#include <random>


#define SAFE_DELETE( p )       { if( p ) { delete ( p );     ( p ) = NULL; } }
#define SAFE_DELETE_ARRAY( p ) { if( p ) { delete[] ( p );   ( p ) = NULL; } }
#define SAFE_RELEASE( p )      { if( p ) { ( p )->Release(); ( p ) = NULL; } }
// TODO: reference additional headers your program requires here

#include "Utils.h"
#include "Manager.h" // this object uses utils
#include "Bot.h"    // this object uses utils
#include "LinkedList.h"
#include "Village.h"  // this object will use utils in the future

链接器错误消息:

Manager.obj : error LNK2005: "int __cdecl Utils::GetRandomBetween(int,int)" (?GetRandomBetween@Utils@@YAHHH@Z) already defined in Bot.obj stdafx.obj : error LNK2005: "int __cdecl Utils::GetRandomBetween(int,int)" (?GetRandomBetween@Utils@@YAHHH@Z) already defined in Bot.obj c:\users\lee\documents\visual studio 2010\Projects\AI\Debug\AI.exe : fatal error LNK1169: one or more multiply defined symbols found

还可能值得注意的是,在我的 Manager 类标题中,我转发了声明 Bot. 与 Village 类标题相同。

4

2 回答 2

11

您的函数定义(即:源代码)不应在标题中。您获得多个定义的原因是extern无法将函数定义(源代码)转换为函数声明(即:只是原型)。所以你需要这样做:

实用程序.h:

namespace Utils
{
    int GetRandomBetween(int low, int high);
};

SomeSourceFile.cpp(可能是 Util.cpp):

namespace Utils
{
    int GetRandomBetween(int low, int high);
    {
        if (low < 0 || low >= high)
            return 0;
        int seed = high - low;

        return (rand() % seed) + low;
    }
};

或者,您可以inline在标头中声明该函数:

namespace Utils
{
    inline int GetRandomBetween(int low, int high)
    {
        if (low < 0 || low >= high)
            return 0;
        int seed = high - low;

        return (rand() % seed) + low;
    }
};

虽然你应该只将它用于小功能。

于 2011-08-05T22:27:25.753 回答
2

Manager.cpp两者Bot.cpp都包括Util.h

因此,在编译它们时,两个目标文件都会导出符号“GetRandomBetween”。当链接器将这些目标文件组合成一个可执行文件时,它会找到该函数的 2 个实例。链接器无法确定使用哪一个(并且它不理解它们是相同的)。

如果您想让目标文件不导出符号(这样您就不会遇到链接器冲突),请删除 extern 关键字。

于 2011-08-05T22:11:08.260 回答