为什么 strcmp 不知道叮当响



我有一个比较两个字符串的基本程序:

#include <string>
#include <iostream>
using namespace std;
int main (int argc, char *argv[]) {
  if(strcmp (argv[0],"./test") != 0) {
    cout << "not equal" << endl;
  } else {
    cout << "equal" << endl;
  }
  return 0;
}

它使用 gcc 编译,但不使用 clang 编译:

 > clang -o test test_clang.cpp 
test_clang.cpp:7:6: error: use of undeclared identifier 'strcmp'
  if(strcmp (argv[0],"./test") != 0) {
     ^
1 error generated.

为什么它不编译与 clang ?

编辑:人们对堆栈溢出越来越苛刻,以至于我犹豫要不要发布问题。上面的问题有一个简单的答案,很好,但是对问题投反对票(第一分钟两次!)是正常的吗,因为它们有一个简单但不明显的答案?

使用

#include <string.h>

#include <cstring>

而不是

#include <string>

字符串标头用于来自C++的 std::string。string.h 用于以 C 零结尾的字符* 字符串。cstring就像string.h,但C++。

它与 gcc 一起使用的原因可能是不同的警告/错误级别设置。可以在不 #including 标头和声明 strcmp 的情况下编译代码。编译器将无法执行类型检查,但链接器仍会解析该符号。

你也可以完全避免使用 strcmp 并写入

#include <string>
#include <iostream>
int main (int argc, char *argv[]) {
  std::string command = argv[0];
  if( command != "./test" ) {
    std::cout << "not equal" << endl;
  } else {
    std::cout << "equal" << endl;
  }
  return 0;
}

在比较的一侧使用 std::string 将导致 "./test" 字符串也转换为 std::string,并且比较将由 std::string 类的 == 运算符完成。

您没有包含正确的头文件

#include <cstring>
您需要

#include <cstring>(或可能#include <string.h> .)

许多编译器在包含另一个标准标头时会包含额外的标准标头。 标准允许这样做;你有责任使用保证所用内容的声明的标头,而不仅仅是恰好具有编译器声明的标头。

您必须包含<cstring> . <string> 是C++字符串的标头。

最新更新