I've this C code in interface.h
:
#include <iostream>
class A{
void foo();
};
namespace interface{
...
namespace Sounds{
A val;
};
}
I need to call .foo
method.
I want to do it in interface.cpp
:
#include "interface.h"
void A::foo(){
std::cout<<1;
}
interface::Sounds::val.foo();
But Clion warns me:
No type named 'val' in namespace 'interface::Sounds'
What should I do?
CodePudding user response:
You may only declare and define types, functions and objects outside function bodies, thus the compiler looks for the type val
and can't find it. You may call functions without using their returned results only from functions.
int main() {
interface::Sounds::val.foo();
}
Above will be almost successfully compiled, for val
at least. void A::foo()
is declared private, thus could not be accessed at val.foo()
unless it is declared public:
class A {
public:
void foo();
};
CodePudding user response:
There are 2 ways to solve this both of which are shown below.
Method 1: Prior C 17
First method is using the extern
kewyord in the header file for the declaration of val
and then define val
in the source file before using it as shown below:
interface.h
#pragma once
#include <iostream>
class A{
public: //public added here
void foo();
};
namespace interface{
namespace Sounds{
//note the extern here . This is a declaration
extern A val;
};
}
interface.cpp
#include "interface.h"
void A::foo(){
std::cout<<1;
}
//definition
A interface::Sounds::val;
main.cpp
#include <iostream>
#include "interface.h"
int main()
{
//call member function foo to confirm that it works
interface::Sounds::val.foo();
return 0;
}
The output of the above modified program is:
1
Method 2: C 17
You can use inline
instead of extern
with C 17 and onwards to define val
in the header:
interface.h
#pragma once
#include <iostream>
class A{
public: //public added here
void foo();
};
namespace interface{
namespace Sounds{
//note the inline used here
inline A val{};
};
}
interface.cpp
#include "interface.h"
void A::foo(){
std::cout<<1;
}
//nothing needed here as we used inline in the header
main.cpp
#include <iostream>
#include "interface.h"
int main()
{
//call member function foo to confirm that it works
interface::Sounds::val.foo();
return 0;
}