为什么strcmp不知道铿锵?

Bar*_*rth 12 c++ clang 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;
}
Run Code Online (Sandbox Code Playgroud)

它用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.
Run Code Online (Sandbox Code Playgroud)

为什么不用clang编译?

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

Tom*_*rle 16

使用

#include <string.h>
Run Code Online (Sandbox Code Playgroud)

要么

#include <cstring>
Run Code Online (Sandbox Code Playgroud)

代替

#include <string>
Run Code Online (Sandbox Code Playgroud)

所述标头是从C++中的std :: string.string.h用于C零终止char*字符串.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;
}
Run Code Online (Sandbox Code Playgroud)

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


obm*_*arg 11

您没有包含正确的头文件

#include <cstring>
Run Code Online (Sandbox Code Playgroud)


asc*_*ler 5

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

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