读书人

写多文档时用extern出现的连接有关问题

发布时间: 2012-03-12 12:45:33 作者: rapoo

写多文档时用extern出现的连接问题
这是 "try.h ":
int add(int a,int b);
-----------------
这是 "try.cpp "
#include "try.h "
int a;
int b;
int add(int a,int b)
{
int c;
c=a+b;
return c;
}
---------------------
这是main.cpp
#include "try.h "
#include <iostream.h>


extern "C " int a;
extern "C " int b;
void main()
{

int c;
a=3;b=4;
c=add(a,b);
cout < <c < <endl;

}
结果编译时出现以下问题:
Linking...
main.obj : error LNK2001: unresolved external symbol _b
main.obj : error LNK2001: unresolved external symbol _a
Debug/trying.exe : fatal error LNK1120: 2 unresolved externals

请各位帮帮忙

[解决办法]
1. 全局变量最好不要同函数形参同名.
2. 在.h中用extern

//try.h
#ifndef TRY_H
#define TRY_H

extern int A;
extern int B;

int add(int a,int b);

#endif

//只在一个.cpp中定义一次全局变量
//try.cpp
#include "try.h "
int A;
int B;
int add(int a,int b)
{
int c;
c=a+b;
return c;
}

//在其他.cpp中直接使用
#include "try.h "
#include <iostream>
using namespace std;
int main()
{

int c;
A=3;B=4; //直接使用
c=add(A,B);
cout < <c < <endl;

return 0;

}



[解决办法]
在main.cpp中去掉
extern "C " int a;
extern "C " int b;
在try.h中加上
extern "C " int a;
extern "C " int b;

[解决办法]
C里没有extern "C ", C++才有

读书人网 >C++

热点推荐