簡體   English   中英

為什么GCC中的-Wunused-variable即使在靜態const上也會產生錯誤?

[英]Why does -Wunused-variable in GCC produce an error even on static const?

我有一個標題, core/types.hh ,由幾個不同的構建目標使用。 它有以下聲明:

core/types.hh

typedef std::size_t  Size;

static const Size SZ_MAX = std::numeric_limits<Size>::max();
...

一些目標使用這個常數,有些則沒有。 所以我得到:

error: 'core::SZ_MAX' defined but not used"

我在Linux上使用帶有GCC 4.7.3的scons。 我有-Wall設置,並希望保持這種方式。

據我從GCC文檔中了解,這不應該發出警告:

-Wunused-variable

除了聲明之外,每當局部變量或非常量靜態變量未使用時發出警告。 -Wall.啟用此警告-Wall.

所以我不明白為什么我會收到警告(這會變成錯誤)。

在其他答案中,建議人們在extern聲明並在使用常量的文件中進行賦值。 許多其他文件都使用此文件,因此如果我這樣做,它將失去其常量。 此外,這個文件有標題保護,所以我認為這應該意味着常量實際上只創建一次。

我很感激任何幫助!

尤瓦


可能重復:

似乎這不是停止編譯的錯誤。

相反,如果GCC發現另一個錯誤,它仍然會報告這一點。

我實際上有另一個未使用的變量,這就是首先導致此錯誤的原因。

例如,在創建以下文件時:

file1.cc

#include "head1.hh"

int main() {
    int bad_unused_variable;
    return my_ns::JUST_ANOTHER_CONST;
}

head1.hh

#ifndef HEAD1
#define HEAD1

#include <stdint.h>
#include <cstddef>
#include <limits>

namespace my_ns {
    typedef std::size_t Size;
    static const Size SZ_MAX = std::numeric_limits<Size>::max();
    static const Size JUST_ANOTHER_CONST = 8;
}

#endif

你得到:

> g++ -Wall -Werror file1.cc -O2 -std=c++98 -o file1
file1.cc: In function 'int main()':
file1.cc:4:6: error: unused variable 'bad_unused_variable' [-Werror=unused-variable]
In file included from file1.cc:1:0:
head1.hh: At global scope:
head1.hh:10:20: error: 'my_ns::SZ_MAX' defined but not used [-Werror=unused-variable]
cc1plus: all warnings being treated as errors

編輯這似乎也在這里得到了回答: gcc警告:已定義但未使用vs未使用的變量 - 他們提到了兩個警告消息之間的細微差別( unused variable與已defined but not used )。 盡管如此,它並沒有真正回答為什么 GCC表現得這樣......

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM