C++中errno变量的类型是什么?
What is the type of the errno variable in C++?
我正在用 C++ 进行一些系统编程,我想将 linux 系统中的 errno 变量传递给我的异常处理程序。您可以在此处查看示例代码
https://pastebin.com/ppgMc8Hj
#include <sys/stat.h>
#include <cerrno>
#include <iostream>
#include <cstring>
std::string errorString(int errno){
return std::strerror(errno);
}
int main(){
struct stat sb;
errno = 0;
if(stat("/jdfj/", &sb)){
errorString(errno);
}
else{
std::cout << std::boolalpha << S_ISDIR(sb.st_mode) << std::endl;
}
}
但它 returns 像这样的错误
In function 'int main()':
14:26: error: invalid conversion from 'int' to 'int* (*)()' [-fpermissive]
6:13: note: initializing argument 1 of 'std::string errorString(int* (*)())'.
我在这里看到 http://en.cppreference.com/w/cpp/string/byte/strerror returns 来自 errno 的字符串的标准函数接受一个 int 作为参数。
我的问题是
- 如果是int类型为什么在上面的代码中不起作用?
- 如果不是,它是什么类型?
errno
是一个实现定义的宏,它扩展为 int
.
类型的表达式
问题是您使用名称 errno
作为函数参数,这是不允许的。由于名称 errno
是一个宏,因此它被展开了。对我来说,结果是 std::string errorString(int (*_errno()))
。如果您更改参数名称,您的代码片段可以正常工作。
std::string errorString(int error_num){
return std::strerror(error_num);
}
除了 François 的回答之外,让我们看看预处理器在带有 GCC 的 Linux 系统上的输出是什么。 g++ -E test.cpp
给出:
# 6 "test.cpp"
std::string errorString(int
# 6 "test.cpp" 3 4
(*__errno_location ())
# 6 "test.cpp"
){
return std::strerror(
# 7 "test.cpp" 3 4
(*__errno_location ())
# 7 "test.cpp"
);
}
所以这里errno
定义为(*__errno_location ())
。其实是一个函数调用,但是如果你把int
放在前面,它恰好也是一个合法的参数声明。
宏赞。
我正在用 C++ 进行一些系统编程,我想将 linux 系统中的 errno 变量传递给我的异常处理程序。您可以在此处查看示例代码 https://pastebin.com/ppgMc8Hj
#include <sys/stat.h>
#include <cerrno>
#include <iostream>
#include <cstring>
std::string errorString(int errno){
return std::strerror(errno);
}
int main(){
struct stat sb;
errno = 0;
if(stat("/jdfj/", &sb)){
errorString(errno);
}
else{
std::cout << std::boolalpha << S_ISDIR(sb.st_mode) << std::endl;
}
}
但它 returns 像这样的错误
In function 'int main()':
14:26: error: invalid conversion from 'int' to 'int* (*)()' [-fpermissive]
6:13: note: initializing argument 1 of 'std::string errorString(int* (*)())'.
我在这里看到 http://en.cppreference.com/w/cpp/string/byte/strerror returns 来自 errno 的字符串的标准函数接受一个 int 作为参数。 我的问题是
- 如果是int类型为什么在上面的代码中不起作用?
- 如果不是,它是什么类型?
errno
是一个实现定义的宏,它扩展为 int
.
问题是您使用名称 errno
作为函数参数,这是不允许的。由于名称 errno
是一个宏,因此它被展开了。对我来说,结果是 std::string errorString(int (*_errno()))
。如果您更改参数名称,您的代码片段可以正常工作。
std::string errorString(int error_num){
return std::strerror(error_num);
}
除了 François 的回答之外,让我们看看预处理器在带有 GCC 的 Linux 系统上的输出是什么。 g++ -E test.cpp
给出:
# 6 "test.cpp"
std::string errorString(int
# 6 "test.cpp" 3 4
(*__errno_location ())
# 6 "test.cpp"
){
return std::strerror(
# 7 "test.cpp" 3 4
(*__errno_location ())
# 7 "test.cpp"
);
}
所以这里errno
定义为(*__errno_location ())
。其实是一个函数调用,但是如果你把int
放在前面,它恰好也是一个合法的参数声明。
宏赞。