visual studio-Vc++/c++强制包含标头异常

visual studio - Vc++/c++ Force Include Header Exception

本文关键字:包含标 异常 studio-Vc++ c++ visual      更新时间:2023-10-16

所以我一直在使用makefiles和g++在Linux中开发一个项目,但现在我想让它在Visual Studio上的Windows中运行。所以我的项目有一个特殊的cpp和.h文件。只有1。我配置了.h,使其自动包含在除特殊cpp文件之外的所有cpp文件中。然而,我在Visual Studio中似乎无法做到这一点。

我基本上是在写我自己的vcxproj文件,所以我查找了配置设置,并在设置中找到了Force Include标志。但我似乎找不到破例的办法。

我还尝试修改.h文件,以便它能够识别它是从哪里包含的,并通过预处理指令(如#if和"__file__")表现出不同的行为。但我发现"__FILE__"会以任何一种方式返回.h,而不是源。

我在谷歌上搜索的想法和关键词都用完了。有什么想法或线索吗?

提前感谢。

编辑:

在Linux上运行的示例代码:

Special.h

class Test{
private:
Test() = delete;
Test(const Test&) = delete;
Test(Test&&) = delete;
public:
    void print(const char*);
};
extern TEST t1;

Special.cpp

#include <iostream>
class Test{    //Singleton Class
private:
Test();    //Note that this line is different from the .h
Test(const Test&) = delete;
Test(Test&&) = delete;
public:
    static Test& getInstance();    //Note that this line is missing from the .h
    void print(const char*);
};
Test::Test(){}
Test& Test::getInstace(){
    static Test inst;
    return return inst;
}
void Test::print(const char* msg){
    std::cout << msg << std::endl;
}
Test t1 = Test::getInstance();    

主要.cpp

int main(){
    t1.print("Hello World!");
}

Makefile:

all: App-Main
App-Main: Main.o Special.o
    g++ Main.o Special.o
Special.o: Special.cpp
    g++ -c $< $@ -std=c++11
%.o: %.cpp
    g++ -c $< $@ -std=c++11 -include Special.h

这是迄今为止在Linux中运行的代码。没有生成错误什么都没有。如果我们在Special.cpp中包含Special.h,则会出现问题。目前,请假设有理由不在cpp文件中包含.h文件。

头文件和源文件中定义Test。删除源文件中的类定义,只保留成员函数实现。


当您要求预处理器#include一个文件时,它实际上包括了#include指令所在位置的实际内容。

预处理后,您的文件看起来像

...
class Test{
public:
    void print(const char*);
};
class Test{
public:
    void print(const char*);
};
void Test::print(const char* msg){
    std::cout << msg << std::endl;
}

最简单的解决方案是在各处#包含"Special.h"。当然,它有一个头球后卫。现在在"Special.cpp"的编译中,还要传递/D=SPECIAL_H_HEADERGUARD。标头仍将在物理上包含,但在逻辑上跳过。

当然,你想要这样做的原因(故意违反ODR)是相当可疑的,并且不能保证实际结果。例如,链接时间代码生成(LTCG)违反了您的"愚蠢链接器"假设。