【问题标题】:Werror missing declarations in C++ with SFML带有 SFML 的 C++ 中缺少声明的错误
【发布时间】:2020-12-07 20:00:20
【问题描述】:

我正在使用带有 SFML lib 的 C++ 制作游戏,我主要创建了几个函数。我知道主要这样做是一种不好的方式,但是是的。当我尝试编译代码时出现错误:

src/main.cpp: In function 'void create_platforms(std::vector<std::unique_ptr<sf::Sprite> >&)':
src/main.cpp:12:6: error: no previous declaration for 'void create_platforms(std::vector<std::unique_ptr<sf::Sprite> >&)' [-Werror=missing-declarations]
 void create_platforms(std::vector<std::unique_ptr<sf::Sprite>>& platforms)
      ^~~~~~~~~~~~~~~~src/Player.cpp:
 In member function 'void Player::gravity(sf::Time&, sf::FloatRect&)':

create_items 和 create_interface 也是如此。我没有为 main.cpp 使用任何头文件,我可以在 main.cpp 中声明它们吗?如果是这样,如果有人能帮助我怎么做,我会很高兴。

void create_platforms(std::vector<std::unique_ptr<sf::Sprite>>& platforms)
{
    [...]
}

void create_items(std::vector<std::unique_ptr<sf::Sprite>>& healing_items)
{
    auto small_heart = std::make_unique<sf::Sprite>();
    small_heart->setTexture(*TextureManager::getTexture("heart"));
    small_heart->setPosition(320, 180);
    small_heart->setScale(0.4, 0.4);
    healing_items.emplace_back(std::move(small_heart));
}

void create_interface(std::vector<std::unique_ptr<sf::Sprite>>& interface)
{
    auto life = std::make_unique<sf::Sprite>();`enter code here`
    life->setTexture(*TextureManager::getTexture("life"));
    life->setPosition(10, 530);
    interface.emplace_back(std::move(life));
}

int main()
{
    [...]
}

【问题讨论】:

标签: c++ sfml


【解决方案1】:

我可以在 main.cpp 中声明它们吗?

技术上是的。 -Wmissing-declarations 选项重要的是声明在定义之前。您放置声明的文件无关紧要。

但是请注意,这可能与警告的精神背道而驰。当您同时不想使用标头时,为什么要收到有关缺少声明的警告,目前尚不清楚。

如果该函数打算仅在该翻译单元中使用,那么您应该在匿名命名空间中声明它。 -Wmissing-declarations 不会对匿名命名空间中的函数发出警告。

【讨论】:

  • If the function is intended to be used only within that translation unit, then you should declare it within an anonymous namespace. 我不明白那个说法。它可以在任何命名空间中。如果必须限制在翻译单元之外不可见,则函数应声明为static,否则其他单元中可用的声明必须在同名的命名空间中进行
  • @Swift-FridayPie It can be in any namespace. 当然可以。但是如果它不需要在其他地方使用,那么不给命名空间命名会更容易,因为这会引入跨不同翻译单元的名称冲突的可能性。 function should be declared static 与使用匿名命名空间相比,这有什么优势?据我所知,它有效地实现了同样的目标。
  • 编辑澄清:不给命名空间命名更容易,因为命名会引入名称冲突的可能性。
  • 同意这一点。只是匿名命名空间带来了自己的问题和优势,应该小心对待......不完全等同于用静态指定的内部链接,对于它们仍然在全局符号表中留下错误名称的函数,一些不小心的使用可能会导致 ODR 违反,如果他们类型声明和他们与 tempate 专业化的使用是麻烦的。
  • 从我收集到的 OPs 代码中,情况正好相反:main.cpp 中的那些函数将在 Player.cpp 中使用,这需要在该模块中声明
猜你喜欢
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
  • 2012-11-05
相关资源
最近更新 更多