Hi -
Code:
// a.h
#ifndef _A_H
#define _A_H
#ifdef __cplusplus
extern "C" {
#endif
int SUB();
#ifdef __cplusplus
}
#endif
extern char *B;
#endif /*_A_H */
Code:
// a.cpp
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include "a.h"
char *B = NULL;
int
main(int argc, char *argv[])
{
B = (char *)calloc(1,200);
strcpy (B, "Hello" );
printf ("B: %s\n", B);
SUB ();
printf ("B: %s\n", B);
return 0;
}
Code:
// b.cpp
#include <string.h>
#include "a.h"
int
SUB()
{
strcpy (B, "Good bye");
return 0;
}
Some notes:
1. To "share a variable between modules", just:
a) Declare the "extern" (EXAMPLE: in "a.h")
b) Define the variable (EXAMPLE: in "a.cpp")
2. You don't need "#define MAIN". That used to be necessary in very, very old C compilers. Most modern compilers now allow you to have the "extern" declaration visible in the same file as your actual definition.
3. Your local header should be quoted:
Code:
//Good
#include "a.h"
//Poor
#include <a.h>
You should only use "<>" with system headers (like "<stdio.h>").
4. You should define a "guard" for each header (EXAMPLE: "#ifndef _A_H/#define _A_H/.../#endif")
5. Like tuxdev suggested, "extern "C" {}" is only needed if you plan on calling a subroutine from both C and C++. You should "guard" your extern "C" with "#ifdef __cplusplus", so it will compile in either/both environments.
6. If you define "int main()",then you need to "return" some integer (else you'll probably get a compiler error).
7. When you define your global pointer, "char *B", you should *always* initialize it to NULL.
8. You should only "#include" those headers actually needed by the source file (in contrast to Microsoft style, which likes to put everything under the sun into one big "stdfx.h" header). For example, in "a.h", you don't need *any* #include's.
'Hope that helps .. PSM