C ++的putenv警告 [英] putenv warning with C++

查看:121
本文介绍了C ++的putenv警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在使用g++编译的程序中使用putenv stdlib函数,包括标志和警告-std=c++11-Wall -Wextra.

I am trying to use putenv stdlib function in a program that I am compiling with g++ including the flags and warnings -std=c++11 and -Wall -Wextra.

程序可以像下面这样简单:

The program can be as easy as the following:

#include<stdlib.h>
#include<iostream>
int main(int argc, char *argv[])
{
    putenv("LD_LIBRARY_PATH=../Desktop/lib");
    std::cout<<"hello\n";
    return 0;

}

但是我收到此错误warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings].

据我在C ++中的理解,我应该声明:char const *str =,但随后putenv在抱怨.

As far as I understood in C++ I should declare: char const *str = but then putenv is complaining.

我知道我可以转换,但是有没有适当的方法在C ++中使用putenv函数,还是应该完全避免使用C函数?

I know I could cast but is there a proper way to use putenv function in C++ or being it a C function it should be completely avoided?

推荐答案

std::getenv 是C ++标准(以及C标准)的一部分,但将来会选择 一种 语言,您可以使用该语言实际编程在您的情况下是C ++), putenv 函数是"t.

While std::getenv is part of the C++ standard (and the C standard as well, but in the future pick one language, the one you really program in which in your case is C++), the putenv function isn't.

从链接的POSIX参考中可以看到 putenv ,其参数为char *类型.

As you can see from the linked POSIX reference for putenv, it's argument is of type char *.

这非常重要,C和C ++之间有一点不同:在C中,可以将文字字符串传递给期望char *的函数.在C ++中,所有文字字符串都是 恒定 ,并且只能传递给期望const char *的函数.

This is very important, and one thing that differs between C and C++: In C a literal string can be passed to functions expecting char *. In C++ all literal strings are constant and can only be passed to functions expecting const char *.

要解决您的问题,您需要使用初始化后的非常数数组,然后传递:

To solve your problem, you need to use a non-constant array that you initialize and then pass:

char env[] = "LD_LIBRARY_PATH=../Desktop/lib";
putenv(env);

重要说明:该数组在程序的整个生命周期内必须有效.这意味着即使在main函数返回之后.

Important note: The array must be valid during the full life-time of your program. That means even after the main function returns.

setenv 函数,该函数既将const char *作为其参数(因此可以与文字字符串一起使用),并且还复制了这些参数,这意味着范围和生存期没有问题.

A better solution (and mentioned in a comment) is the setenv function, which both takes const char * for its argument (and can therefore be used with literal strings) and also copies the arguments which means there's no problem about scope and life-time.

关于字符串文字.在C和C ++中,它们实际上都是字符数组.区别在于,在C ++中,数组是恒定的.

Regarding string literals. In both C and C++ they are really arrays of characters. The difference is that in C++ the arrays are constant.

这篇关于C ++的putenv警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆