【问题标题】:Preventing multiple definition in C++ [duplicate]防止 C++ 中的多重定义 [重复]
【发布时间】:2021-09-07 05:14:55
【问题描述】:

我收到错误:

/usr/bin/ld: /tmp/ccCbt8ru.o: in function `some_function()':
Thing.cpp:(.text+0x0): multiple definition of `some_function()'; /tmp/ccc0uW5u.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status

在构建这样的程序时:


ma​​in.cpp

#include "common.hpp"
#include "Thing.hpp"

int main() {
    some_function();
}

common.hpp

#pragma once
#include <iostream>

void some_function() {
    std::cout << "something" << std::endl;
}

Thing.hpp

#pragma once

class Thing {
public:
    void do_something();
};

Thing.cpp

#include "Thing.hpp"
#include "common.hpp"

void Thing::do_something() {
    some_function();
}

我正在编译:g++ main.cpp Thing.cpp -o main.out

我也尝试过使用包含保护而不是#pragma once,但它似乎也不起作用。有什么我忘记了吗?

【问题讨论】:

  • 包含保护防止在单个 cpp 文件中包含多个标题(技术术语:翻译单元)。您有多个 cpp 文件。每个都包括。每个都有自己的some_function 定义。考虑制作some_functioninline

标签: c++ g++ multiple-definition-error


【解决方案1】:

#pragma once 和包含守卫只能防止多个定义在单个翻译单元中.cpp 文件)。各个单元彼此一无所知,因此不可能删除多重定义。这就是为什么当链接器链接目标文件时,它仍然会看到多个定义。

要解决此问题,请将common.hpp 更改为:

#pragma once

void some_function();

这告诉编译器有一些some_function 的代码。 然后,添加一个文件common.cpp,其中包含common.hpp 标头的代码:

#include "common.hpp"
#include <iostream>

void some_function() {
    std::cout << "something" << std::endl;
}

最后,将g++命令改为:

g++ main.cpp common.cpp Thing.cpp -o main

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 2019-01-21
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多