Following an example at: http://www.learncpp.com/cpp-tutorial/47-structs/ relating to structs, and when I tried to compile this program:
#include <iostream>
void PrintInformation(Employee sEmployee)
{
std::cout<<"ID: "<<sEmployee.nID<<std::endl;
std::cout<<"Age: "<<sEmployee.nAge<<std::endl;
std::cout<<"Wage: "<<sEmployee.fWage<<std::endl;
}
struct Employee {int nID;int nAge;float fWage;};
int main()
{
Employee abc;
abc.nID=123;
abc.nAge=27;
abc.fWage=400;
// print abc's information
PrintInformation(abc);
return 0;
}
I get the following:
Why is that?
Thanks.
You need to declare the struct before the function that attempts to use it.
C (and by extension, C++) were designed for "single-pass" compilation. Therefore, everything must be available to the compiler by the time it's required.
Related
I have a class that has a declared method but not defined/used anywhere. I expected this piece of code to generate linking error but it did not. Looks like compiler is smart enough to remove dead code. Which default optimization is doing this? How can I explicitly disable it to generate the error?
#include <iostream>
using namespace std;
class Base{
public:
int x;
string name;
void set(int val){ x = val;};
int get(){ return x;}
void Init();
};
int main() {
Base base;
base.set(10);
cout << base.get() << endl;
return 0;
}
EDIT1: Here Init() function is not defined and neither used anywhere. So, I expected compiler to complain about this not defined. But don't see any error/warning.
Thanks in advance.
Generally the linker will only produce errors for undefined symbols that are used. As you never call Init there is no error.
Looks like compiler is smart enough to remove dead code.
The compiler is not even "smart" here. There is no code using a function so that function is not needed to produce an executable program.
The function is not even "ODR used" so technically the compiler would be wrong to require a definition.
This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 7 years ago.
Ok so I'm still getting used to C++ again, so this error may seem simple. I'm attempting to create a simple class with a three member functions (I'm only trying to call one of them in this). So I create the class, instantiate an object, then attempt to call the function using that object and this error comes up:
Code.cpp:(.text+0x15): undefined reference to `Code::genCode()'
I've double checked to see if it was an error with the function itself, but that is not the case. I've seen others post about this issue but there seems to be a multitude of situations and solutions. Anyway here's the code:
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <list>
using namespace std;
class Code {
public:
int genCode();
int checkCorrect();
int checkIncorrect();
};
int main()
{
Code c1;
c1.genCode();
}
////////////////FUNCTIONS/////////////////////////
int genCode()
{
vector <int> newcode;
srand(time(NULL));
for(int i = 0; i < 9; i++){
int x;
x = (rand() % 6);
if (find(newcode.begin(),newcode.end(), x) == newcode.end())
{
newcode.push_back(x);
}
}
if (newcode.size() > 4)
{
newcode.pop_back();
}
for(int i = 0; i < 4; i++)
{
return newcode[i];
}
}
int checkCorrect()
{
}
int checkIncorrect()
{
}
you need to put class name before method name
the format is
'returnType Classname::methodname
{
codes
}'
int code::genCode()
{
//codes
}
or you also possible to write code in class
Change the implementation of the methods of your class to the following:
int Code::genCode()
{
...
}
int Code::checkCorrect()
{
...
}
int Code::checkIncorrect()
{
...
}
You are defining the functions outside the class. Put them inside the class, then you don't need to declare them inside the class. Directly define them.
#include <vector>
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
#include <list>
using namespace std;
class Code {
public:
////////////////FUNCTIONS/////////////////////////
int genCode()
{
cout << "Inside genCode. Just for Debugging purpose." << endl;
vector <int> newcode;
srand(time(NULL));
for(int i = 0; i < 9; i++){
int x;
x = (rand() % 6);
if (find(newcode.begin(),newcode.end(), x) == newcode.end())
{
newcode.push_back(x);
}
}
if (newcode.size() > 4)
{
newcode.pop_back();
}
for(int i = 0; i < 4; i++)
{
return newcode[i];
}
}
int checkCorrect()
{
}
int checkIncorrect()
{
}
};
int main()
{
Code c1;
c1.genCode();
}
Otput:
Inside genCode. Just for Debugging purpose.
The function
int genCode()
Is what's called a free function. It is not bound to a class.
In order for the compiler to know that genCode is part of a class, you have to tell it by explicitly stating the namespace to which genCode belongs.
int Code::genCode()
However since it appears code Code is entirely contained within one file, following CodeRunner's advice will lead to a cleaner implementation.
But why would anyone want to got the trouble of splitting everything up?
Separating the class definition from the method implementations allows you place the class definition into one file, the 'h header file, and the methods in an implementation file, usually a .cpp file. The header file is then shared with users of the Code object and the implementation file can be compiled into a library and hidden from the callers view.
There are a number of reasons to do this, but most of them have to do with creating pre-compiled libraries and using them to reduce build times.
With a library, you build the library once, and then compile the rest of the code that uses the library over and over until you get it right. Can you imagine how long it would take to build a program if you had to rebuild the C++ standard library every time you fixed a bug and wanted to test?
Had a job like that once. Had to spend four hours compiling third party network code every time I made a fix because the company's paranoid build system rebuilt everything every time. Off by one error? 4 hours. Need to add a debug line? 4 hours. You could make and test three changes a day. Sure, you can batch up a bunch of fixes, but if one failed spectacularly and broke the system, which one was it? Sooner or later you're reduced to a crawl, making tweaks, building, testing, profiling one at a time. Fortunately I was working on contract and paid by the hour.
Another good example is you can have one library that supports Windows and other libraries supporting QNX and other operating systems. All use the same header and the user can write a program that, in theory, will operate on all supported platforms simply by recompiling the user's code. It's never quite that clean, but one can dream.
The library can even be replaced with an updated library without requiring changes or compilation of the user's code and different variants of the library can exist for different needs. A debug version with extra logging, for example.
Perhaps the implementation is not intended for public eyes. The users get to see the header and call functions in the library, but no more.
I have a query for creating c++ object inside c file.
I have the sample code below. When trying to import the CPlusHeader it throws an error which i could not understand.
The error is iostream' file not found as one of the error. How could i resolve this issue.
Regards,
Lenin
CPlusFile.h
include iostream
include string
using namespace std;
class CPlusFile {
int data;
public:
CPlusFile();
int getData();
};
CPlusFile.cpp
CPlusFIle::CPlusFIle() {
data = 10;
}
int CPlusFile::getData() {
return data;
}
CFile.h
int doSomething();
CFile.c
include "CFile.h"
include "CPlusFile.h"
int doSomething() {
CPlusFile object;
}
It strongly depends on what you call a "C file". Previous answer assumed that you meant a file with a .c suffix. I assume here that you mean a file that shall be compiled with a C compiler.
If my assumption is valid, then the answer is simple: You cannot instantiate C++ classes in a C file. What you can do, though, is call C++ static methods from the C code. Please refer, for example, to In C++ source, what is the effect of extern "C"? to see how to do this.
First of all, it is
#include <iostream>
#include <string>
and not
include iostream
include string
Second, if CFile.c is compiled as C, then this will not work. The C compiler will not understand the class keyword and you cannot create an instance of a class in C.
iostream is a C++ header, and isn't available if you're compiling using a C compiler. You can write C++ code in a .c file, you just need to use the right compiler.
You can use this in your C++ header file to check wether you are going to include it from C or C++ code:
#ifdef __cplusplus
The includes iostream and others, as well as using class, are only available for C++ code.
But if you want to use the CPlusFile class, which is a C++ class, you can only do that in C++ code. Best is to rename your CFile.c to CFile.cpp.
Yes, it is possible to call C++ object inside the C file. Here I performed a scenario and
it's working fine for me.
CPlusFile.h
#include<iostream>
#include<string>
using namespace std;
class cplus{
int data;
public:
cplus();
int getdata();
};
CPlusFile.cpp
#include "cplusfile.h"
cplus::cplus(){ data =10; }
int cplus::getdata(){ return data; }
CFile.h
#include "cplusfile.h"
#include<stdio.h>
int dosomething();
CFile.c
#include "cfile.h"
int dosomething(){
cplus c;
printf("%d",c.getdata());
}
int main() {
dosomething();
return 0;
}
And compile this by g++ CFile.c CPlusFile.cpp and it works fine.
Say I have two different cpp files. Both declare classes with the same name, but perhaps a totally different structure (or perhaps the same structure, different implementation). The classes do not appear in the header files. (As an example, suppose they are Node classes for different list classes.)
I've seen these classes conflict. Is this expected by the standard? What solutions are there to this problem?
UPDATE:
As suggested by answers/comments, anonymous namespaces are what I was looking for.
The standard way around this problem is to wrap the classes in different namespaces.
It violates One Definition Rule. It's hard for compiler to detect the error, because they are in different compilation units. And even linker cannot detect all errors.
See an example in http://www.cplusplus.com/forum/general/32010/ . My compiler and linker (g++ 4.2.1) can build the final executable without any error, but the output is wrong.
If I change the example a bit, I get segmentation fault.
// main.cpp
#include <iostream>
#include <list>
using namespace std;
struct Handler
{
Handler() : d(10, 1.234) {}
list<double> d;
};
extern void test_func();
int main(void)
{
Handler h;
cout << h.d.back() << endl;
test_func();
return 0;
}
// test.cpp
#include <iostream>
#include <string>
using namespace std;
struct Handler
{
Handler() : d("test Handler") {}
string d;
};
void test_func()
{
Handler h;
cout << h.d << endl;
}
It's recommended to differentiate you class by namespace. For example of Node, you can use nest class and define the Node in the parent list class. Or you can add you class in anonymous namespace. See How can a type that is used only in one compilation unit, violate the One Definition Rule?
I'm not sure if I'm missing some detail here, but you wrap each class in a namespace.
namespace A {
class Node { };
}
namespace B {
class Node { };
}
Then you can use A::Node or B::Node.
You can use namespace to have multiple classes with same name by sub-scoping them in different namespaces. See: http://www.cplusplus.com/doc/tutorial/namespaces/
I've seen these classes conflict. Is this expected by the standard?
The standard says you can't do that. It would violate the one definition rule. (How to fix this has already been covered in other answers)
id.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class A
{
public:
static int a;
};
int A::a=20;
class b
{
public:
b()
{
cout<<A::a<<endl;
}
};
int main()
{
b *b1 = new b();
return 0;
}
id1.cpp
#include "stdafx.h"
#include <iostream>
using namespace std;
class c
{
public:
int get()
{
cout<<A::a<<endl;
}
};
int main()
{
c c1;
c1.get();
return 0;
}
This is the way they have declared and got the output in one program but when I'm trying it I'm getting errors as the class is not a namespace or the program id is not included in the id1 file... How to get the variable that is stored in one file into the other file without using namespace and including the header file is there any option for it?
Two separate programs as shown (they're separate because they both define main()) cannot share variables in any simple way.
If the two separate files were to be integrated into a single program, so one of the main() programs was replaced, then you would fall back on the standard techniques of declaring the variable A::a in a header and using that header in both modules. The header would also define class A. This is the only sane way to do it.
You could write the definition of the class twice, once in each file, and declare the variable as an extern in one file and define it in the other, but that is not particularly sensible even in this simple case and rapidly degenerates into unmaintainable disaster if the code gets any more complex and there are more shared variables.
Of course, you might want to consider not using a global variable at all, but provide instead an accessor function. However, you still end up with a header declaring the services provided by the class A and the code implementing those services, and the code consuming those services.