const char*的多个定义

Multiple definition of a const char*

本文关键字:定义 char const      更新时间:2023-10-16

我得到了全局的上述消息链接器错误

const char* HOST_NAME = "127.0.0.1";

我不认为我已经编译了两次文件,但这是我对文件的定义。

main.cpp

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include "connection.hpp"

连接.cpp

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <arpa/inet.h>
#include "connection.hpp"

连接.hpp

#ifndef __connection__
#define __connection__
#include <unistd.h>
#include <netinet/in.h>
const int BUFFSIZE = sysconf(_SC_PAGESIZE);             //Define page size
const char* HOST_NAME = "127.0.0.1";                    //Local host
//Definition of a class
#endif

有什么帮助吗?

您对字符串使用了错误的声明。您需要将字符串设为常量,因为常量可能以多个编译单元定义。这就是为什么编译器不会为BUFFSIZE报告相同的错误:BUFFSIZE是常量,因此它可能在不同的编译单元中定义多次。但是HOST_NAME不是常数,所以它被报道。如果您将HOST_NAME的声明更改为,它将是常量

const char* const HOST_NAME = "127.0.0.1"; 

然后错误应该会消失。


[C++11: 3.5/3]:具有命名空间作用域的名称(3.3.6(如果是的名称,则具有内部链接

  • 明确声明为static的变量、函数或函数模板;或者
  • 显式声明为constconstexpr且既没有显式声明extern也没有先前声明为具有外部链接的变量;或
  • 匿名联合的数据成员

这有效地使定义它的每个翻译单元都具有恒定的"局部性",消除了冲突的机会。

不要以为我已经编译了两次文件

然而,事情就是这样。您已经多次编译connection.hpp,每次都将# include编译成一些翻译单元。

static添加到声明,或者将extern添加到声明中,删除= somestring部分,并在一个源文件中提供定义。

您在connection.cpp和main.cpp中都包含了"connection.hpp"。因此,它(const char* HOST_NAME = "127.0.0.1";(在2个cpp文件中定义。

相关文章: