如何避免“多重定义"?全局常数错误? [英] How to avoid "multiple definition" error for global constants?
问题描述
我正在使用Windows API编写C程序.每个主要功能都有其自己的文件,并且原型具有一个标头,并包含诸如此类的内容:
I'm writing a C program using the Windows API. Each major function has its own file, and there is one header for the prototypes and includes and whatnot:
// Headers & global constants
#pragma once
#define _WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <WindowsX.h>
#include <Windef.h>
#define szClassName TEXT("EthicsPresentationWnd")
// Prototypes
LRESULT CALLBACK WindowProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam);
BOOL CALLBACK FontProc1(HWND hWnd, LPARAM lParam);
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd);
ATOM RegisterWindow(HINSTANCE hInstance);
让我烦恼的是#define szClassName
行.我不喜欢使用宏,而是希望有一个适当的全局变量wchar_t szClassName[]
,但是如果这样做,链接器会抱怨每个包含标头的模块中的乘法定义变量.
The thing I'm irritated about is the #define szClassName
line. I dislike using macros and would prefer to have a proper global variable, wchar_t szClassName[]
, but if I do that then the linker complains about multiply defined variables in each of the modules that include the header.
我以为#pragma once
指令可以阻止这种情况,但事实并非如此.
I thought the #pragma once
directive would prevent this, but it didn't.
这个问题有解决方案吗?
Is there any solution to this problem?
推荐答案
解决方案是使用单独的声明和定义...
The solution to this is to have a separate declaration and definition...
标题(* .h;对不起,我不知道WinAPI类型名称,请根据需要进行调整):
Header (*.h; sorry, I don't know WinAPI type names, adapt as necessary):
extern const char szClassName[];
实施(* .c或* .cpp)
Implementation (*.c or *.cpp)
const char szClassName[] = "hello, world"
您正在看到问题,因为每次您的* .c或* .cpp文件之一包含标头(即使包含include防护!)时,都会声明一个新符号szClassName
;这会使链接器感到困惑(请参阅下文).
You're seeing the problem because a new symbol szClassName
is being declared each time one of your *.c or *.cpp files includes the header (even with the include guards!); and that makes the linker confused (see below).
请注意,这将使sizeof(szClassName)
不再起作用.
Do note that this will make sizeof(szClassName)
not work anymore.
预处理后,编译器基本上会看到以下内容:
After preprocessing, the compiler is basically seeing this:
- 文件"a.c":
const char someSymbol[] = <some text, don't care what right now>;
- 文件"b.c":
const char someSymbol[] = <some text, don't care if it's the same>;
- 文件"c.c":
const char someSymbol[] = <some text, ditto>;
- file "a.c":
const char someSymbol[] = <some text, don't care what right now>;
- file "b.c":
const char someSymbol[] = <some text, don't care if it's the same>;
- file "c.c":
const char someSymbol[] = <some text, ditto>;
当链接器链接目标文件(例如,"a.obj","b.obj"和"c.obj")时,它会看到使用新值(至少就链接器而言)---并因此失败并显示错误.
When the linker is linking the object files (say, "a.obj", "b.obj" and "c.obj"), it sees the same symbol being defined with a new value (at least as far as the linker is concerned) --- and thus it fails with an error.
这篇关于如何避免“多重定义"?全局常数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!