关闭

C/C++ extern practices

267人阅读 评论(0) 收藏 举报

Good style of using extern keyword in C/C++:

For variables, like int, float, pointers, please declare them in .h files, then define them in respective .cpp file, for example,

t1.h:

#ifndef T1H
#define T1H
#include <iostream>
using namespace std;

extern int a;
extern char g_str[7];
extern char* p_str;

void func1();

#endif

t1.cpp:

#include "t1.h"

int a = 10;
char g_str[] = "123456";
char* p_str = (char*)"test in t1.cpp";

void func1()
{
	cout << "func1(), a:" << a << endl;
	cout << "func1(), g_str:" << g_str << endl;
	cout << "func1(), p_str:" << p_str << endl;
}

t2.h:

#include "t1.h"
#include <iostream>
#include <string.h>

using namespace std;

void func2();
static void func3();

t2.cpp:

#include "t2.h"

void func2()
{
	a = 11;
	cout << "func2(), a:" << a << endl;

	g_str[0] = '9';
	// Can't use g_str = "873654", array is not modifiable l-values,
	// so use strcpy() to change them.
	strcpy(g_str, "873654");
	cout << "func2(), g_str:" << g_str << endl;

	p_str = (char*)"test in t2.cpp";
	cout << "func2(), p_str:" << p_str << endl;
}

static void func3()
{
	cout << "static func3()." << endl;
}

test_extern.cpp:

#include <stdio.h>
#include <iostream>
#include "t1.h"
#include "t2.h"

using namespace std;

// if we not include respect .h file, using extern to declare function prototype, which tell current module to 
// find this function in other modules; if we include .h, still could declare function prototype, but no necessary
extern void func2();

int main()
{
	func1();
	func2();
	// func3() is static function, static function only can used in its owning module, 
	// if called in other module then compiling error occurs.
	// func3();
	return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:293904次
    • 积分:4101
    • 等级:
    • 排名:第7524名
    • 原创:89篇
    • 转载:379篇
    • 译文:2篇
    • 评论:12条
    文章分类
    最新评论