-2

I am a newbie programmer in C++, I already know that I can use extern keyword to access functions and global variables on the other files in my project but the problem that I faced to, is that how can I use structs, enums placed (available in other files of my project) in my current .cpp file?

T.I.A

Niall
  • 28,102
  • 9
  • 90
  • 124

1 Answers1

1

You should declare them in a header file, then #include them when you need them. You can still define them in a cpp file.

Cory Kramer
  • 98,167
  • 13
  • 130
  • 181
  • What about placing them in namespaces? – Amir Hashemieh Sep 29 '14 at 11:53
  • That is good practice too, but won't help you if you declare and define them in the cpp file. Then no other file can see them unless they include the cpp file, which is a bad idea! – Cory Kramer Sep 29 '14 at 11:54
  • Don't forget that you can use [#ifndef](http://stackoverflow.com/a/1653965/1694735) to avoid redefinitions – Bruno Camarneiro Sep 29 '14 at 11:58
  • @camb8 That is not necessary in this case, they do not sound like they are declaring macros, they are defining `enum`s and `struct`s, etc. – Cory Kramer Sep 29 '14 at 11:59
  • So using headers in the only solution!? – Amir Hashemieh Sep 29 '14 at 11:59
  • 1
    Unless you only have 1 cpp file for your whole project, yes. If you define something in a cpp file, there is no way any other cpp file can see it, unless it is declared in a header file elsewhere. That is why you always see `Class.h` and `Class.cpp`, so you can just `#include "Class.h"` even though it doesn't have the full definitions. – Cory Kramer Sep 29 '14 at 12:01