const char*的多个定义
Multiple definition of a const char*
我得到了全局的上述消息链接器错误
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
的变量、函数或函数模板;或者- 显式声明为
const
或constexpr
且既没有显式声明extern
也没有先前声明为具有外部链接的变量;或- 匿名联合的数据成员
这有效地使定义它的每个翻译单元都具有恒定的"局部性",消除了冲突的机会。
不要以为我已经编译了两次文件
然而,事情就是这样。您已经多次编译connection.hpp
,每次都将# include
编译成一些翻译单元。
将static
添加到声明,或者将extern
添加到声明中,删除= somestring
部分,并在一个源文件中提供定义。
您在connection.cpp和main.cpp中都包含了"connection.hpp"。因此,它(const char* HOST_NAME = "127.0.0.1";
(在2个cpp文件中定义。
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 在标准中,模板参数的语法在哪里定义,例如,'std::function<int(char)>'?
- 为什么从 char 转换为 std::byte 可能是未定义的行为?
- 从 std::string 到 std::array<char,size> 的 memcopy 额外数据是否是一种未定义的行为?
- 将结构 std::memcpy 转换为具有足够容量的 std::vector 是未定义的行为<char>吗?
- 包括"lvtocon.h",未定义对'operator<<(std::ostream&, char const*)的引用
- 未定义模板"std::__1::basic_istringstream<char, std::__1::char_traits<char>, std::__1::allocator&
- C++ 如何检查 char 变量是否未定义(未初始化)
- 将字符串文本常量定义为 char const* 和 wchar const*
- 定义.cpp中常数int/char*
- 仅使用 bool 和 char 定义一个 templete 类
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- 来自 cpp首选项的用户定义的 const char* 文字示例
- gtest - 未定义对"testing::InitGoogleTest(int*, char**)"的引用
- Qt5 对'QApplication::QApplication(int&, char**, int)'的未定义引用
- 自定义char*插入功能多次运行时会产生运行时错误
- 如何在 C++ 中安全地为 char *array 重新分配内存(它适用于自定义字符串类)
- [lex.ccon] 中 c-char 的定义可能存在矛盾
- 定义char数据类型,并与sprintf一起使用
- 定义 char 和 int 时指针有什么区别