1

我需要一些关于如何设置我的项目的建议。我正在构建一个静态库,并想在我走得太远之前知道我使用预编译头文件的方式是否正确。

到目前为止,我的 stdafx 文件只包括(对于 DWORD 等类型)和(对于 std::string)。

我构建了一个名为 TestFuncs.cpp/h 的简单 cpp/header 组合

TestFuncs.cpp:

#include "stdafx.h"
using namespace std;
void MyFunc(DWORD a, string b) {
    // irrelevant
}

测试函数.h

#pragma once
void MyFunc(DWORD a, std::string b);

此处的代码可以正确编译。我遇到的问题是,当我想在另一个项目中使用这个静态库时,我通常会执行 #include "path_to_my_static_lib_project/TestFuncs.h"

但是,这个问题基于 TestFuncs.h,DWORD 和字符串在当时都是未知的,因为它们是从 stdafx.h 文件定义的类型。

我想出的一种解决方案(我不知道这样做是否正确)只是在 #pragma once 之后将 stdafx.h 包含在 TestFuncs.h 的顶部。现在项目工作文件是否使用预编译头文件。

这是应该如何完成的,还是有正确的方法?

谢谢你。

4

1 回答 1

5

不要#include "stdafx.h"在你的库的公共头文件中。通过公共头文件,我的意思是您的库的客户端将使用的头文件#include

相反,只定义绝对最小值,并且最好在此文件中使用 100% 可移植代码。如果您的库将被不同的编译器或平台使用,也应避免使用 STL。

因此,假设您有一个my_library.hgizmo.cpp. 您将拥有以下内容:

小工具.cpp

#include "stdafx.h"
#include "my_library.h"

int GizmoTronic()
{ 
  // ...
  return 42;
}

此外,题外话,但使用宏保护而不是#pragma onceC++ 语言的一部分,因此并非所有编译器都支持。进入是一个坏习惯。

编辑:

至于你的标题是 -ed 时没有被定义的问题DWORD,我有 3 条建议:string#include

1) 只使用可移植的数据类型。也就是说,标准定义的数据类型。 DWORD是微软的一项发明(几十年前)。它不是语言的一部分,也不是可移植的。相反,使用unsigned long或其他合适的东西。

2) Don't use string in your library's public interface if your library is going to be used by code compiled with a compiler other than yours. The reason is because string is defined completely in header files, so each compiler potentially has it's own implementation. One compiler's string might look different from another's.

3) Assuming #2 doesn't apply, feel free to #include any necesarry headers from the Standard Library at the top of your header. If you use string in your public interface, #include <string> in your header. (Just please do not using namespace std). Your header should be self-contained.

EDIT2:

Here is how I would declare your function:

void MyFunc(unsigned long a, const char* b);
于 2010-11-15T03:42:11.437 回答