'numeric_limits'未在此范围内声明,没有匹配函数用于调用'max()'

Mat*_*son 20 c++ ignore max cin numeric-limits

我在我的mac/xcode上编译了这个代码,没有任何问题.我在学校用linux上的g ++编译它,我得到这些错误:

:'numeric_limits'不是std的成员
:'>'标记之前的预期primary-expression
:没有用于调用'max()'的匹配函数

#include <iostream>
#include <cstdlib>

using namespace std;

int GetIntegerInput(int lower, int upper)
{
    int integer = -1;
    do
    {    
        cin >> integer;
        cin.clear();
        cin.ignore(std::numeric_limits<streamsize>::max(), '\n');  //errors here
    }while (integer < lower || integer > upper);

    return integer;    
} 
Run Code Online (Sandbox Code Playgroud)

我猜对了也许我必须加一个额外的标题.如果我带走了std ::它只是给了我一个类似的错误

'numeric_limits'未在此范围内声明

Ada*_*eld 52

您需要包含头文件<limits>,这std::numeric_limits是定义的位置.您的Mac编译器通过自动包含该头文件来帮助您; 但是,您不应该依赖该行为并明确包含您需要的任何头文件.

  • 这个功能有名字吗?我想弄清楚如何禁用它,所以我不打破平台独立性. (7认同)

arz*_*eth 12

GCC 11 开始明确要求包括<limits>, <memory>, <utility><thread>根据https://www.gnu.org/software/gcc/gcc-11/porting_to.html#header-dep-changes

Clang 12(或更早的版本,我不知道)也有相同或相似的故事。

由于我在使用yarn(Node.js 的包管理器)时(经常)遇到此错误,并且它每次都会覆盖所有源文件,因此我无法轻松添加:在编译过程中,#include <limits>我需要 fork 或垃圾邮件。cp /tmp/fixedBad.h /installdir/bad.h

因此我的解决方案是添加到 CXXFLAGS (不是 CFLAGS):

-include /usr/include/c++/11/limits(Ubuntu 21.04,海湾合作委员会11.1.0)

-include /usr/include/c++/11.1.0/limits(Arch Linux;版本相同,但路径与 Debian/Ubuntu 不同)

或者优雅地:-include /usr/include/c++/11*/limits

请注意,*仅当由 shell(bash、sh、zsh 等)或 makefile 使用时才有效。换句话说,gcc 和 clang 不注意*文件路径,因此如果您使用ninja build或直接从 C 程序向 gcc/clang 传递参数,请小心。

我有这个/etc/environment

#CPPFLAGS="-D_FORTIFY_SOURCE=2 -DNDEBUG"
CPPFLAGS="-D_FORTIFY_SOURCE=2"
CFLAGS="-g -pipe -march=native -mtune=native -Ofast -pipe -ftree-vectorize -fstack-protector-strong"
CXXFLAGS="-g -pipe -march=native -mtune=native -Ofast -pipe -ftree-vectorize -fstack-protector-strong -include /usr/include/c++/11*/limits"
LDFLAGS="-Wl,-O1,--sort-common,--as-needed,-z,relro"
RUSTFLAGS="-C target-cpu=native -C opt-level=2"
Run Code Online (Sandbox Code Playgroud)

检查echo $CXXFLAGS,如果更改未应用,请重新启动 shell 或操作系统,或注销当前 tty,或切换到另一个 tty,或仅在终端中运行:

export CXXFLAGS="-g -pipe -march=native -mtune=native -Ofast -pipe -ftree-vectorize -fstack-protector-strong -include /usr/include/c++/11*/limits"
Run Code Online (Sandbox Code Playgroud)

或者set -a; source /etc/environment; set +a;

我还尝试添加到 CXXFLAGS-include '<limits>'-include '<limits.h>',但它说“没有这样的文件或目录”

我还有另一个解决方案(非常脏):

将其添加到/usr/include/stdint.h(或stdlib.h其他一些流行的文件)最后一行 ( #endif) 之前:

#ifdef __cplusplus
extern "C++" {
       #include <limits>
}
#endif
Run Code Online (Sandbox Code Playgroud)

Ubuntu 21.04 和 Debian Busterdpkg-query -S /usr/include/stdlib.h 表示其归libc6-dev:amd64. Arch Linuxpacman -Qo /usr/include/stdlib.h表示它的所有者是glibc. 所以当包更新时这个hack会被覆盖,不要忘记。