14

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

#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 编译?

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

4

4 回答 4

18

采用

#include <string.h>

或者

#include <cstring>

代替

#include <string>

字符串标头用于 C++ 中的std::string。string.h用于 C 零终止的 char* 字符串。cstring类似于 string.h 但用于 C++。

它与 gcc 一起工作的原因可能是不同的警告/错误级别设置。可以在没有#include 标头和声明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;
}

Using a std::string on one side of the comparison will cause the "./test" string to be converted into a std::string as well and the comparison will be done by the == operator of the std::string class.

于 2012-06-21T12:16:52.770 回答
11

您没有包含正确的头文件

#include <cstring>
于 2012-06-21T12:15:42.713 回答
5

您需要#include <cstring>(或可能#include <string.h>。)

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

于 2012-06-21T12:16:44.713 回答
3

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

于 2012-06-21T12:15:56.433 回答