关于 c :Compiling Helper file with functions

Compiling Helper file with functions

我不知所措 - 我刚刚进入 C 语言,但由于某种原因,这对我来说不起作用。所以我正在使用 Netbeans,并且我有以下主文件:

1
2
3
4
5
6
7
8
9
10
11
12
#include <cstdlib>

#include"functions.h"

using namespace std;

int main(int argc, char** argv) {

    f("help");

    return 0;
}

Functions.h 文件:

1
2
3
4
5
6
7
8
#include <string>

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

void f( string a );

#endif

和 Functions.cpp 文件:

1
2
3
4
5
#include"functions.h"

void f( string a ) {
    return;
}

所以,长话短说,它不能编译。它说它无法理解字符串变量?我不明白,我尝试将字符串的包含移动到整个地方,但似乎无济于事。我该怎么办?


你需要在Functions.h中包含字符串头文件,同时告诉编译器string来自std命名空间。

1
2
3
4
5
6
7
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <string>
void f( std::string a );

#endif

Functions.cpp 文件:

1
2
3
4
5
#include"functions.h"

void f( std::string a ) {
    return;
}

更好的做法是通过 const 引用传递字符串

1
2
3
void f(const std::string& a ) {
    return;
}

请参阅为什么 \\'using namespace std;\\' 在 C 中被认为是一种不好的做法?


如果您尝试使用 std::string,则必须在函数头中添加 #include <string>,并将其命名为 std::string,因为它位于 std 命名空间中。

1
2
3
4
5
6
7
8
#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include <string>

void f( std::string a );

#endif

请参阅此相关帖子以及为什么在 C 中"使用命名空间标准"被认为是不好的做法?


包括标准标题:<string>

1
#include <string>