gpt4 book ai didi

c++ - 外部变量导致多重定义错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:00 26 4
gpt4 key购买 nike

我一直在尝试使用 extern 来使用之前定义的变量。

我以前没有使用过 extern,现在我需要使用它来只定义一次变量并在多个文件中使用它们

我已经为这个问题编写了最小化版本的代码。我有四个文件

库文件

#ifndef LIB_H
#define LIB_H

#include <iostream>

namespace lib {

extern bool initialized;

bool initialized = false;

static void isInit(char* parent) {
std::cout << "Library for [" << parent << "] initialized? " << (::lib::initialized ? "yes" : "no") << "\n";
}
} // namespace lib
#endif

车辆.h

#ifndef _VEHICLE_H
#define _VEHICLE_H
#include <string>

class Vehicle {
public:
Vehicle(const std::string& manufacturer,
const std::string& model,
int year);
std::string manufacturer;
std::string model;
int year;
};
#endif

以下是名为vehicle.cpp的vehicle.h文件的实现

#include "vehicle.h"

#include "lib.h"

Vehicle::Vehicle(const std::string& manufacturer,
const std::string& model,
int year) :
manufacturer(manufacturer),
model(model),
year(year) {
::lib::isInit("Vehicle");
}

主要.cpp

#include "vehicle.h"

#include "lib.h"

int main(int argc, char** argv) {

::lib::isInit("main");

::lib::initialized = true;

::lib::isInit("main");

Vehicle vehicle("Toyota", "Corolla", 2013);

return 0;
}

我正在使用 g++

g++ -Wno-write-strings main.cpp vehicle.cpp -o bin/main.cpp.bin 

我收到以下错误:

/tmp/cclVpsgT.o:(.bss+0x0): multiple definition of `lib::initialized'
/tmp/ccmJKImL.o:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status

我已经检查了输出:

g++ -Wno-write-strings main.cpp vehicle.cpp -E

每次包含 lib.h 时都会发生多次定义。

我的问题是:

  • 为什么有 define guard 时 lib.h 被包含多次
  • 我如何定义“extern”变量并在同一文件中对其进行初始化(因为稍后会在同一文件中使用它)

最佳答案

Why is lib.h included multiple times when define guard is there

您需要删除定义:

bool initialized = false;

并将其放在一个且唯一的源文件中。

Include guards 防止同一个头文件在同一个 中被多次包含 translation unit(TU) 不在不同的翻译单元中。
您在头文件中定义变量 initialized,它包含在不同的翻译单元中,然后每个 TU 都有一个名为 initialized 的符号,它打破了 one definition rule

How would I define 'extern' variable and initialize it in the same file (since it's used in the same file later)

如果要在同一个文件中使用变量,为什么要把它设为extern?当您想要在不同的 TU 之间共享相同的变量时,您需要使用 extern
如果您需要在全局范围内仅在单个 TU 中使用它,您应该简单地将它放在 unnamed namespace

关于c++ - 外部变量导致多重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com