strcpy 在 Windows 上编译,但在 Linux 上不编译

strcpy compiles on Windows but it doesn't on Linux

本文关键字:编译 Linux 但在 strcpy Windows      更新时间:2023-10-16

我正在学习C++并尝试编写通用代码(抱歉,我不知道您如何调用可以在Windows,Linux,MacOS等上编译的代码(。

我已经编写了函数trimLeft:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const string rows = "rows:";
const string columns = "cols:";
const string data = "data:";
struct dimensions {
    int rows;
    int columns;
};
inline bool exists (const string& name) {
    ifstream f(name.c_str());
    return f.good();
}
string trimLeft(const string& input) {
    if ((input.empty()) || 
        ((input.at(0) != ' ') && (input.at(0) != 't')))
        return input;
    else {
        char * tab2 = new char[input.length() + 1];
        char *trimmed = new char[input.length() + 1];
        strcpy(tab2, input.c_str());
        bool skip = true;
        int pos = 0;
        for (unsigned int i = 0; i < (input.length() + 1); i++) {
            if (skip) {
                if ((tab2[i] == ' ') || (tab2[i] == 't'))
                    continue;
                else {
                    skip = false;
                    trimmed[pos] = tab2[i];
                    pos++;
                }
            }
            else {
                trimmed[pos] = tab2[i];
                if (tab2[i] == '')
                    break;
                else
                    pos++;
            }
        }
        string stringTrimmed(trimmed);
        return stringTrimmed;
    }
}

它在Windows上编译,显示以下警告:

警告 C4996:"strcpy":此函数或变量可能不安全。 请考虑改用strcpy_s。要禁用弃用,请使用 _CRT_SECURE_NO_WARNINGS。

但在 Linux 中,使用以下命令:

g++ FormatMatrix.cpp -o 格式

我得到:

error: ‘strcpy’ was not declared in this scope

每个操作系统上的标头是否不同?


请停止投反对票:我收到了信息。

作为特定编译器的实现细节,<cstring> ,包括strcpy声明,完全有可能被你包含的另一个标头包含(也许在包含树的更远的地方(。

为了确保你的代码是真正可移植的,并且符合标准,请包括你调用的每个类和函数的头文件;永远不要想当然地认为通过包含不同的东西来获得另一个头文件的功能。