C/C++ extern practices

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;
}


你可能感兴趣的:(C/C++ extern practices)