I have a program with two external files in addition to main.cpp and a header of constants. So in total four files. They contain the following code:
main.cpp
#include <iostream> using namespace std; int ext1_func(); int ext2_func(); int main() { int i; i = ext1_func(); cout << i << endl; i = ext2_func(); cout << i << endl; return 0; } ext1.cpp
#include "const.h" int asd1=1; int ext1_func() { return temp_int; } ext2.cpp
#include "const.h" int asd2 = 2; int ext2_func() { return temp_int; } const.h
#ifndef CONST_H #define CONST_H const int temp_int=1; #endif My desired is the following:
1) Any variables declared in ext1.cpp should be known only to functions within ext1.cpp and likewise for ext2.cpp. So "asd1" must only be known to "ext1_func" and "asd2" for "ext2_func".
2) The functions in "exp1.cpp" and "ext2.cpp" must be able to see all values defines in "const.h"
I believe that the code I have written and attached satisfies these requirements, but I would like to ask if I am doing it correctly? Is there an easier way to obtain the desired behavior than what I have suggested?
Thanks in advance.
Niles.
asdNvariables are visible outside their source files (discussed in extenso in the various answers), and (2) there isn't a header declaring the functions that is used to enforce consistency between the code using the functions (main.cpp) and the code defining the functions (extN.cpp). Granted, C++ has type-safe linkage (unlike C, where I mainly work). However, in general, it is best not to write extern declarations in source files — there should be a header that declares the functions that is used to enforce consistency.