Why do I not need to include main.cpp? - c++

In the small example needsExtern.cpp needs the definition of global::bar. needsExtern.cpp would normally include the file with the definition (in this case main.cpp). However, since the file is main.cpp it is not needed.
Why does needsExtern.cpp not need to include main.cpp?
needsExtern.h
struct NeedsExtern
{
NeedsExtern();
};
needsExtern.cpp
#include "needsExtern.h"
#include <iostream>
namespace global
{
extern const int bar;
}
NeedsExtern::NeedsExtern()
{
std::cout << global::bar << "\n";
}
main.cpp
#include "needsExtern.h"
namespace global
{
extern const int bar{26};
}
void main()
{
NeedsExtern ne;
}

This is precisely where extern is invented for: the compiler just assumes the variable is defined elsewhere in the project. You can read more about this principle here.

Related

How to use extern to link to a function in other cpp file?

Here is my main.cpp:
#include <iostream>
#include "function.cpp"
using namespace std;
extern int giveMain();
int main() {
int x = 4;
x = giveMain(x);
cout << x << endl;
}
And here is my function.cpp:
#include <iostream>
using namespace std;
int giveMain(int a) {
a = 3 + a;
return a;
}
But when I compile, it says that "Linker command failed". Can anyone helps me to solve this problem.
You declared the function int giveMain() in main.cpp but the function in function.cpp takes an int. Declare the correct function and it should work. Also extern is the default for functions so you don't need to include the keyword.
EDIT: Just noticed that you #include <function.cpp> in main.cpp. Never include .cpp files. The issue you were having was multiple definitions for int giveMain(int) because the contents of functions.cpp was being compiled twice.

Static variable link error, C++

Consider this code.
//header.h
int x;
//otherSource.cpp
#include "header.h"
//main.cpp
#include "header.h"
...
int main()
{
}
In this case compiler erred with the message. "fatal error LNK1169: one or more multiply defined symbols found"
but when I add static before x, it compiles without errors.
And here is the second case.
//header.h
class A
{
public:
void f(){}
static int a;
};
int A::a = 0;
/otherSource.cpp
#include "header.h"
//main.cpp
#include "header.h"
...
int main()
{
}
In this case compiler again erred with multiple declaration.
Can anybody explain me the behavior we static variables in classes and in global declarations?? Thanks in advance.
The issue with the static member variable is that you have the definition occur in the header file. If you #include the file in multiple source files, you have multiple definitions of the static member variable.
To fix this, the header file should consist only of this:
#ifndef HEADER_H
#define HEADER_H
// In the header file
class A
{
public:
void f(){}
static int a;
};
#endif
The definition of the static variable a should be in one and only one module. The obvious place for this is in your main.cpp.
#include "header.h"
int A::a = 0; // defined here
int main()
{
}
Declare x as extern in header.h to tell the compiler that x will be defined somewhere else:
extern int x;
Then define x once in the source file which you think is most fitting.
For example in otherSource.cpp:
int x = some_initial_value;

operator declaration within namespace in a header?

Please excuse me but I didn't know to give a name to the title in a short way.
Why do I need to declare an overloaded operator inside the header to make it work in this example:
HEAD.H
#pragma once
namespace test {
class A {
public:
A() : x(0) {}
int x;
};
A& operator++(A& obj); //this is my question
}
HEAD.CPP
#include "head.h"
namespace test {
A& operator++(A& obj) {
++obj.x;
return obj;
}
}
MAIN.CPP
#include <iostream>
#include "head.h"
using namespace std;
using namespace test;
int main() {
A object;
++object; //this won't work if we delete declaration in a header
return 0;
}
operator++ is defined and declared in a namespace inside "head.cpp" so why do I need to declare it one more time in a header?
Thank you.
The CPP files are compiled independently of each other, and they only see the header files they've included (which are in fact textually added to the source code of the CPP before compilation). As such you'll use the header file to inform the compiler that a function exists with that signature (be it an operator overload).
Then the output from your CPP files is put together by the linker, which is when you'd find out if for instance you had declared a function in a header file but never taken the trouble to implement it.
Simple example with namespaces:
#include <iostream>
namespace test{
int f() { return 42; }
int g() { return -1; }
}
namespace other{
int f() { return 1024; }
}
using namespace other;
int main(){
//error: 'g' was not declared in this scope
//std::cout << g() << std::endl;
std::cout << test::f() << std::endl; //42
std::cout << f() << std::endl; //1024
return 0;
}

Error : **** has not been declared

In my Function.h file:
class Function{
public:
Function();
int help();
};
In my Function.cpp file:
#include "Function.h"
int Function::help() //Error here
{
using namespace std;
cout << "Help";
return 1;
}
In my Main.cpp
#include <iostream>
#include "Function.h"
using namespace std;
int menu(){
Function fc;
fc.help();
return 1;
}
int main(int args, char**argv){
return menu();
}
Error is : ‘Function’ has not been declared
Can anybody tell me why? Thank you.
I tried like this and the problem is solved, but I dont really understand why:
In Function.h file:
I use
class Function{
public:
int status;
Function():status(1){}
int help();
};
instead of the old one
class Function{
public:
Function();
int help();
};
All your include statements are missing the #:
#include "Function.h"
^
Everything else looks fine, though you need to also #include <iostream> in Function.cpp since you're using cout.
Here is the Function.cpp that I got to compile and run:
#include "Function.h"
#include <iostream>
int Function::help() // No error here
{
using namespace std;
cout << "Help";
return 1;
}
Function::Function()
{
}
I had a similar problem. Make sure that you only have the required header files. I had two header files both including each other and it spit out this mistake.
You have created a declaration for the constructor of the Function class without including it in your implementation (cpp file).
#include "Function.h"
Function::Function(){
// construction stuff here
}
int Function::help() //Error here
{
using namespace std;
cout << "Help";
return 1;
}
In the first Function.h file you have declared the constructor but not defined it. In the second Function.h file (the one that works) you have defined and declared the Function constructor. You can either define and declare in the header or file, or declare in the header file and define in the Function.cpp file.
For example, declare in the header file "Function.h":
class Function
{
Function();
}
and define here in "Function.cpp":
Function::Function(){}
Or the alternative is to declare and define in the header file "Function.h":
Class Function
{
Function(){}
}
The other thing that you have done in the second version of the header file is to initialise the member variable "status" in the "member initialisation list" which is a good thing to do (See Effective C++ by Scott Meyers, Item 4). Hope this helps :)

Reference C++ struct object in another file?

I'm in the process of trying to make a game-in-progress more modular. I'd like to be able to declare a single array of all the room_t objects in the game (room_t rooms[]), store it in world.cpp and call it from other files.
The truncated code below does not work, but it's as far as I've gotten. I think I need to use extern but have not been able to find a method that works correctly. If I try and declare the array in the header file, I get a duplicate object error (as each file calls world.h, I'd assume).
main.cpp
#include <iostream>
#include "world.h"
int main()
{
int currentLocation = 0;
cout << "Room: " << rooms[currentLocation].name << "\n";
// error: 'rooms' was not declared in this scope
cout << rooms[currentLocation].desc << "\n";
return 0;
}
world.h
#ifndef WORLD_H
#define WORLD_H
#include <string>
const int ROOM_EXIT_LIST = 10;
const int ROOM_INVENTORY_SIZE = 10;
struct room_t
{
std::string name;
std::string desc;
int exits[ROOM_EXIT_LIST];
int inventory[ROOM_INVENTORY_SIZE];
};
#endif
world.cpp
#include "world.h"
room_t rooms[] = {
{"Bedroom", "There is a bed in here.", {-1,1,2,-1} },
{"Kitchen", "Knives! Knives everywhere!", {0,-1,3,-1} },
{"Hallway North", "A long corridor.",{-1,-1,-1,0} },
{"Hallway South", "A long corridor.",{-1,-1,-1,1} }
};
Just add extern room_t rooms[]; in your world.h file.
world.h
extern room_t rooms[];
The problem is that you're trying to reference a variable you've declared in the .cpp file. There's no handle on this outside of the scope of this file. In order to fix this, why not declare the variable in the .h file but have an Init function:
room_t rooms[];
void Init();
Then in the .cpp
void Init() {
// create a room_t and copy it over
}