必须把两个文件合到一起才能编译通过?
//do.h
void splus(string &s)
{
s=s+"good!";
}
//main.cpp
#include <iostream>
#include <string>
#include "do.h"
using namespace std;
splus(string &s);
int main(int argc,char *argv[])
{
string ss="hello,";
splus(ss);
std::cout<<ss<<endl;
}
wei@wei-Lenovo-G475:~/program$ g++ -Wall -c main.cpp
In file included from main.cpp:3:0:
do.h:1:1: 错误: ‘string’不是一个类型名
main.cpp:5:17: 错误: expected constructor, destructor, or type conversion before ‘;’ token
main.cpp: 在函数‘int main(int, char**)’中:
main.cpp:9:13: 错误: ‘splus’在此作用域中尚未声明
wei@wei-Lenovo-G475:~/program$
后来,我改了,把两个文件合在一个main.cpp里面。
#include <iostream>
#include <string>
using namespace std;
void splus(string &s)
{
s=s+"good!";
}
int main(int argc,char *argv[])
{
string ss="hello,";
splus(ss);
std::cout<<ss<<endl;
}
再没有问题。为什么是这样?
c++中函数和main必须合到一起才能编译通过?
-
- 帖子: 41
- 注册时间: 2013-08-29 9:27
-
- 帖子: 8
- 注册时间: 2011-11-23 12:20
Re: c++中函数和main必须合到一起才能编译通过?
1. 使用std::string前,沒有指定namespace
2. splus()沒有return type
//main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "do.h"
void splus(string &s);
int main(int argc,char *argv[])
{
string ss="hello,";
splus(ss);
std::cout<<ss<<endl;
}
2. splus()沒有return type
//main.cpp
#include <iostream>
#include <string>
using namespace std;
#include "do.h"
void splus(string &s);
int main(int argc,char *argv[])
{
string ss="hello,";
splus(ss);
std::cout<<ss<<endl;
}
-
- 帖子: 39
- 注册时间: 2012-08-20 16:11
Re: c++中函数和main必须合到一起才能编译通过?
首先,就是在相应的头文件中应该包含相应的库文件,比如#include<string>,其次C++是可以有多个编译单元的,比如你里面分开放置的一个do.h和main,在main里面包含你所用到的头文件以及库文件,最后你那个函数的声明会覆盖do.h里面的函数,所以需要注释掉,这还不是最好的,比如还可以用头文件保护符,不多说了,还是找本书看看吧!