cuốn sách gpt4 ai đã làm

c++: .cpp 中的 "Redeclare"外部命名空间变量

In lại Tác giả: Walker 123 更新时间:2023-11-28 04:18:04 hai mươi bốn 4
mua khóa gpt4 Nike

我是 C++ 的新手,遇到了这段代码:

文件.h

namespace Type
{
typedef BOOL (WINAPI *TYCopyFile)
(
PCHAR lpExistingFileName,
PCHAR lpNewFileName,
BOOL bFailIfExists
);
}

namespace Func
{
extern Types::TYCopyFile pCopyFileA;
}

文件.cpp

namespace Funcs
{
Types::TYCopyFile pCopyFileA;
}

void Init
{
Funcs::pCopyFileA = (Types::T_CopyFile) GetProcAddress(hKernel32, "CopyFileA");
}

这个想法很简单。我有 typedef(Types) 的命名空间,并在另一个命名空间 (Funcs) 中创建函数指针作为 extern。然后,我在 Init chức năng File.cpp 中定义该函数指针。

我的问题是,为什么我需要在 File.cpp 中重新声明 namespace Funcs?为什么我不能只使用 Init 函数来初始化 Funcs::pCopyFileA?据我了解 extern,它告诉编译器该变量存在于某处并告诉链接器找到它。如果 File.cpp 中没有 namespace Funcs,为什么链接器无法找到它?

câu trả lời hay nhất

对于 C++ 中的所有符号,您都需要声明定义。头文件包含Func::pCopyFileA的声明,源文件包含定义。

如果您在头文件中定义变量(即删除extern 关键字),那么定义将在所有translation units 中完成。包括头文件。这打破了 one definition rule , 并会在链接时导致多重定义错误。

关于c++: .cpp 中的 "Redeclare"外部命名空间变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56112499/

hai mươi bốn 4 0
Walker 123
Hồ sơ

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá taxi Didi miễn phí
Phiếu giảm giá taxi Didi
Chứng chỉ ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com
Xem sitemap của VNExpress