Header 实施被其他实施取代

Header implementation replaced by other implementation

我想知道我最近尝试过的东西。这并不意味着是生产代码,只是我一起吐出来的东西,并且有一些我无法解释的奇怪行为。也许有更多 C++ 经验的人知道发生了什么。

我有一个 header 文件,其中包含一个 class 以及其中的实现(我猜是暗示编译器将其内联)。我将这个 header 文件包含在编译为 dll 的多个 cpp 文件中;然后我尝试在编译为 lib(静态库)的多个 cpp 文件中使用相同的 header 文件。

并且由于我不需要进入的原因,我无法在该库的 header 中使用 std 的 getcurrentthreadid() API (但相同的 API 编译时没有问题,而 compiling/linking dll)。所以。只是想解决这个问题(我知道这不是一个好的做法,但想尝试一下),我 copy-pasted 原始 header 文件,我删除了对 threadid API,只是硬编码了一个 -1 而不是使用类型的方法。

所以现在我有一个从 cpps 构建的 dll,包括一个带有 threadid 调用的 .h 文件,以及一个从 cpps 构建的 lib,包括一个几乎相同的 .h 文件,硬编码 id = -1。 dll引用了lib文件。

现在,据我所知,在编译 lib 时,header 内容在 pre-compilation 期间被注入到 cpp 文件中,然后进行编译。这意味着 lib 文件应该包含带有硬编码 -1 的 object 代码。 当我随后编译 dll 时,另一个 header 文件被注入到 cpp 文件中,并编译了 cpp 代码。然后,在链接过程中,lib 被加载到 dll 中。

所以我希望在运行时,lib 中的代码使用硬编码的 -1,而 dll 中的代码使用实际的 threadid。但令我惊讶的是,它们似乎都使用实际的 threadid。尽管在编译库时,它抱怨 threadid。

那么,我是否遗漏了所有这些内容?我知道我在做什么不是好的做法,但对结果感到惊讶。 谢谢

您的程序表现出未定义的行为,违反了 One definition rule:

[basic.def.odr]/6 There can be more than one definition of ... inline function with external linkage ... in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. Given such an entity named D defined in more than one translation unit, then

(6.1) — each definition of D shall consist of the same sequence of tokens; and...

实际上,一个典型的实现是让编译器将编译后的函数体发送到使用它的每个目标文件中,并指示链接器选择一个 - 任何一个 - 并丢弃其余的(假设它们都是相同的)。