I was writing a program to search fro a range of prime numbers, and about halfway through to check my progress I decided to build it to make sure everything is working okay, I keep getting error LNK2019! It says it is an unresolved external.I did some research but I don't understand much of anything. Here is the code.
#include <iostream>
using namespace std;
int singlePrime(int subjectNumber);
int main() {
cout<<"Would you like to find a single prime number(1), or a range(2)?"<<endl;
int methodchoice;
cin>>methodchoice;
if(methodchoice ==1) {
int subjectNumber;
cout<<"Which number would you like to test for primeness?"<<endl;
cin>>subjectNumber;
int singlePrime(subjectNumber);
}
if(methodchoice==2) {
int lowRange;
int highRange;
cout<<"Input the low value for your range."<<endl;
cin>> lowRange;
cout<<"Input the high value for your range"<<endl;
cin>> highRange;
for (int index=lowRange; index<highRange;index++) {
if (index=highRange) {
break;
}
singlePrime(index);
}
}
}
Here you declare a function that you never define:
int singlePrime(int subjectNumber);
The linker complains because you invoke this function, but its body is found nowhere.
To verify that this is the problem, replace the declaration with a definition containing some dummy implementation:
int singlePrime(int subjectNumber)
{
return 0;
}
Also notice, that you have a useless initialization of an integer called singlePrime here:
if (methodchoice ==1) {
int subjectNumber;
cout<<"Which number would you like to test for primeness?"<<endl;
cin>>subjectNumber;
int singlePrime(subjectNumber);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Why this?
}
You probably meant this line to do something else (most likely invoke the singlePrime() function), since singlePrime won't be visible outside that block's scope.
It's probably flagging this function prototype:
int singlePrime(int subjectNumber);
You haven't defined a body for the function. You need to implement it (or at least give it a dummy implementation).
Well, my psychic debugging skills have pinpointed the problem. The following code:
int singlePrime(int subjectNumber);
tells the compiler that there exists a function called singlePrime which takes an int and returns an int.
Of course, you then never provide the code for that function... The compiler assumes it's in some other .cpp file and says "oh, well, the linker will take care of that."
And when the linker comes along, it sees that it's supposed to find a function called singlePrime which accepts an int and returns an int. But that function is nowhere to be found.
Simple fix, change:
int singlePrime(int subjectNumber);
into
int singlePrime(int subjectNumber)
{
// some code here to do whatever singlePrime is supposed to do
// be sure to return the correct number. For now, return the
// number of the beast!
return 666;
}
Further down in your code, you seem to try to call this function:
if (methodchoice ==1) {
int subjectNumber;
cout<<"Which number would you like to test for primeness?"<<endl;
cin>>subjectNumber;
int singlePrime(subjectNumber); // What?
}
But this isn't how you call functions in C or C++. You should take a closer look at your book or class notes. You would do something like this:
// call singlePrime and store the result in a variable called
// ret so that we can use it.
int ret = singlePrime(subjectNumber);
And for future reference, it would help if you posted the complete error message you get. You know, in case our crystal balls are malfunctioning because of solar flares.
Related
I want to make a program that will perform some math after reading from user input files.
During the reading process (a function) I want to check if the user syntax in the file is correct, otherwise I would like to shutdown the program so that the user can modify the file(s= accordingly and run it again.
The structure will be something like this:
int main(int argCount, char *args[])
{
std::string fileName = "PathOfFile";
int a = GetUserInput(fileName, variableName);
int b = GetUserInput(fileName, variableName);
// Other functions will be placed here
return 0;
}
int GetUserInput(std::string filename, std::string variableName)
{
// Some routine to read the file and find the variableName
// Some routine to check the syntax of the user input.
// Let us assume that the integers are to be fined as: variableName 1;
// and I want to check that the ; is there. Otherwise, shutdown the program.
}
How can I shutdown the program safely from the function GetUserInput? Is there any C++ to signal that the program must wrap up and exit?
There are many different ways of doing this, the differences are mostly style, personal preferences, and which parts of the C++ library you are familiar with.
The parsing function simply calls exit().
Instead of returning the int value setting, the function takes a pointer or a reference to an int value as an additional parameter and sets it, if valid. The function returns a bool, instead, to indicate whether it parsed a valid setting. main() checks the returned bool value, and itself returns from main(), ending the program.
The parsing function returns a std::optional<int>, instead, returning a std::nullopt to indicate a parsing failure. main() checks the returned value, and itself returns from main(), ending the program.
The parsing function throws an exception that gets caught in main, with the exception handler returning from main.
Each alternative has its own advantages and disadvantages. You can decide, by yourself, which approach works best for your program.
I would suggest to structure your code such that "normal shutdown" is return from main. For example like this
bool GetUserInput(const std::string file,const std::string& variablename,int& a) {
a = ... read value from file...
if (something went wrong) return false;
return true;
}
int main() {
int a;
if (! GetUserInput("file","foo",a)) return 1;
int b;
if (! GetUserInput("file","foo",b)) return 1;
}
You can consider to throw an exception when something goes wrong:
void GetUserInput(const std::string file,const std::string& variablename,int& a) {
a = ... read value from file...
if (something went wrong) throw std::runtime_error("something went wrong");
}
int main() {
int a;
GetUserInput("file","foo",a);
int b;
GetUserInput("file","foo",b);
}
This allows you to catch the exception in main and act accordingly in case you can recover from it. Also you can have different exceptions rater than only a single bool.
If you merely want to exit the program cleanly, you can use std::exit as suggested by πάντα ῥεῖ:
void GetUserInput(const std::string file,const std::string& variablename,int& a) {
a = ... read value from file...
if (something went wrong) std::exit();
}
This will safely shutdown your program (stack is unwound, ie destructors are called, files are closed properly, etc). However, this does not allow you to react on in the caller.
I am not sure why my function is not working. It should be printing out something out (an error message after the user goes out of bounds)I have set the array index at 3 index slots. I'm also getting an error "unused variable 'yourArray' I am not sure where to go from here. Still trying to learn c++ so and advice or help will be greatly appreciated.
#include <iostream>
using namespace std;
class safeArray{
public:
void outofBounds(int,int);
int yourArray[3];
int i;
};
void outofBounds(int,int);
int yourArray[3];
int i;
void outofBounds(int yourArray[],int sizeofArray) {
for (i=0;i<sizeofArray;i++){
cout<<"Please enter integer";
cin >>yourArray[i];
yourArray[i]++;
for (i=0;i>sizeofArray;){
cout<<"safeArray yourArray (" <<yourArray[0]<<","<<yourArray[3]<<")"
<<endl;
}}}
int main() {
void outofBounds(int,int);
int yourArray[3]; //Error: Used variable "yourArray"
};
Your Program is running fine. Unless you added the "-Werror" flag to the compiler, which would treat the "unused variable"-Warning as an Error.
The code compiles fine as seen on here: http://coliru.stacked-crooked.com/a/d648b94f205b51dc
Though your Program does not do what you want it to do, because of the following reasons:
1.) You have 3 redefinitions of outofBounds inside different namespaces:
one inside the classes namespace SafeArray which is a member function
of it
then inside the global space
and then inside the main-function (the entry point)
But the one being actually defined is the one in the global space (2nd one)
2.) You are not passing anything to the function inside main.
define your Array there first then call the function by doing:
int yourArray[3];
outofBounds(yourArray, 3);
3.) You probably wanted to define the member method "outofBounds" inside SafeArray-class. This can be done by writing the scope operator:: which specifies the class to which the member function belongs to:
class SafeArray { // is a class, can also be struct since everything is public anyways
public:
void outofBounds(int,int); // a member of the class SafeArray
// private:
int yourArray[3];
int i;
};
void SafeArray::outofBounds(int yourArray[],int sizeofArray) {
// do something...
}
but then again you need some constructor that initializes the members of your class. Some work needs to be done to make it work, like you want. Good Luck :)
I'm relatively new to c++ and used to Java (which I like better).
I've got some pointer problem here. I created a minimal programm to simulate the behaviour of a more complex programm.
This is the code:
void test (int);
void test2(int*);
int* global [5]; //Array of int-pointer
int main(int argc, char** argv) {
int z = 3;
int y = 5;
cin >> z; // get some number
global[0] = &y; // global 0 points on y
test(z); // the corpus delicti
//just printing stuff
cout << global[0]<<endl; //target address in pointer
cout << &global[0]<<endl; //address of pointer
cout << *global[0]<<endl; //target of pointer
return 0; //whatever
}
//function doing random stuff and calling test2
void test (int b){
int i = b*b;
test2(&i);
return;
}
//test2 called by test puts the address of int i (defined in test) into global[0]
void test2(int* j){
global[0]= j;
}
The tricky part is test2. I put the address of a variable I created in test into the global pointer array. Unfortunately, this program gives me a compiler error:
main.cpp: In function 'int test(int)':
main.cpp:42:20: error: 'test2' was not declared in this scope
return test2(&i);
^
I can't find any scope problem here. I tried changing the int i of test into a global variable, but it didnt help, so I suppose, this isnt the reason.
Edit: It compiles now, but gives for cin = 20 the wrong values. *global[0] should be 400, but is 2130567168. It doesnt seem to be a int/uint problem. It is too far from 2,14e9.
Edit2: The input value doesnt matter.
'test2' was not declared in this scope It's because the compiler doesn't know what test2 is. You need to add a function prototype above the main.
void test (int b);
void test2(int& j);
or just:
void test (int);
void test2(int&);
because at this time compiler only need to know the type of the arguments and not their names.
EDIT: Moving the function definition above the main without adding the prototype will also work, but it's better to use the prototypes.
Before a function can be called, the compiler must know about it.
So you either rearrange your function definitions such that test2 comes first, test second and main last, or you put declarations of test2 and test1 before main:
void test2(int& j); // declaration
void test(int b); // declaration
int main(int argc, char** argv) {
// ...
}
void test(int b){ // definition
// ...
}
void test2(int& j) { // definition
// ...
}
This will then reveal a more serious error; you are calling test2 with an int*, but it expects an int&. You can fix this by turning the call into test2(i);.
Once your functions are neatly split into declarations and definitions, it's time to perform the next step towards the typical C++ source-file management: put the declarations into header files (usually *.h or *.hpp) and #include them from the implementation file (usually *.cpp) that contains main. Then add two more implementation files for the two function definitions. Add corresponding #includes there, too. Don't forget about include guards in the headers.
Finally, compile the three implementation files separately and use a linker to create an executable from the three resulting object files.
you need to declare test2 before you call it. Every function needs to be declared before it is called.
add these lines above main to declare the functions;
void test2(int& j);
void test2(int& j);
int main(){...}
What's the difference between:
void function();
int main()
{......}
void function()
{......}
vs
void function()
{.......}
int main();
It seems odd to declare a function before main then define it after main when you could just declare and define it before main. Is it for aesthetic purposes? My teacher writes functions like the first example.
It's just for code organization purposes ("aesthetics", I guess). Without forward declarations you'd need to write every function before it's used, but you may want to write the bodies of a function in a different order for organizational purposes.
Using forward declarations also allows you to give a list of the functions defined in a file at the very top, without having to dig down through the implementations.
Forward declarations would also be necessary in the case of mutually recursive functions. Consider this (silly) example:
bool is_odd(int); // neccesary
bool is_even(int x) {
if (x == 0) {
return true;
} else {
return is_odd(x - 1);
}
}
bool is_odd(int x) {
return is_even(x - 1);
}
Note I mean to make this answer supplementary, others have already given good answers to this questions.
Note that knowing how to forward declare things in C++ becomes very important. Once you begin using header files it basically becomes mandatory. Header files will allow you to build a prototype of functions and classes/structs then define them in a corresponding .cpp file. This is a very important organizational feature of C++.
// MyClass.h
class MyClass
{
public:
MyClass(int x);
void printInt();
private:
int myInt;
};
// MyClass.cpp
MyClass::MyClass(int x)
{
MyClass::myInt = x;
}
void MyClass::printInt()
{
std::cout << MyClass::myInt;
}
Doing things this way makes it so you're not completely bound to make a huge hodgepodge of code. Especially if you're writing real programs that will have a considerably large amount of source code.
So while in the question you asked forward declaring is really just more of a preference, later on it really won't be a choice.
Your first example is in the Top-Down style, the second in Bottom-Up style.
It's largely aesthetic, in that some people prefer one over the other.
For example, someone might prefer to get a high-level overview of the program before getting the details (top-down), while another might person might prefer to see the details first (bottom-up).
A tangible benefit of the declarations in the top-down approach is that you can more easily re-organize the function definitions without having to worry about ordering.
Look at this example:
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
where, int max(int num1, int num2) is behaving as a function.
Now, here we have a program
#include <iostream>
using namespace std;
// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2)
{
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
I kept max() function along with main() function and compiled the source code. While running final executable, it would produce the following result:
Max value is : 200
Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.
To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.
Let me set the scene..
You can open files in a specific mode like this:
#include <fstream>
int main(){
std::fstream myfile;
myfile.open ("filename", std::ios::app);
return 0;
}
that second parameter is an enumerated type-
which is why you will get a compiler error attempting this:
#include <fstream>
int main(){
std::fstream myfile;
myfile.open ("filename", std::ios::lksdjflskdjflksff);
return 0;
}
In this example, the class doesn't have to account for the second parameter being incorrect, and the programmer never has to worry about passing in a nonsensical value.
Question: Is there a way to write functions that must take a particular type AND a particular value?
Let's say I wanted to re-implement a File Handling class similar to the one above.
The difference is I'm making the second parameter a char instead of an enumerated type.
How could I get something like this to work:
#include "MyFileHandler.h"
int main(){
MyFileHandler myfile1;
myfile.open ("filename", 'a'); //GOOD: a stands for append
myfile.open ("filename", 't'); //GOOD: t stands for truncate
myfile.open ("filename", 'x'); //COMPILER ERROR: openmode can not be the value 'x'
return 0;
}
Going beyond this, can I get the compiler to test the validity of argument values through functional means?
Example:
void IOnlyAcceptPrimeNumbers(const int & primeNumber);
int function(void);
int main(){
IOnlyAcceptPrimeNumbers(3); //GOOD: 3 is prime
IOnlyAcceptPrimeNumbers(7); //GOOD: 7 is prime
IOnlyAcceptPrimeNumbers(10); //COMPILER ERROR: 10 is not prime
IOnlyAcceptPrimeNumbers(10+1); //GOOD: 11 is prime
IOnlyAcceptPrimeNumbers(1+1+1+1); //COMPILER ERROR: 4 is not prime
IOnlyAcceptPrimeNumbers(function()); //GOOD: can this somehow be done?
return 0;
}
void IOnlyAcceptPrimeNumbers(const int & primeNumber){return;}
int function(void){return 7;}
I believe i've made it clear what I want to do and why I find it important.
Any solutions out there?
If you want compile-time checked values, you could write templates rather than function arguments:
template <char> void foo(std::string const &); // no implementation
template <> void foo<'a'>(std::string const & s) { /* ... */ }
template <> void foo<'b'>(std::string const & s) { /* ... */ }
Usage:
foo<'a'>("hello world"); // OK
foo<'z'>("dlrow olleh"); // Linker error, `foo<'z'>` not defined.
If you want an actual compiler error rather than just a linker error, you could add a static_assert(false) into the primary template.
No, if you specify that your function will take a char, it will take any char.
The "resolution" used by the compiler for checking passed arguments is the type rather than a set of possible values.
In other words, you need to use enumerations for this, or move the checking to runtime, or do something horrid like:
static void processAorT (char typ, char *fileName) { ... }
void processA (char *fileName) { processAorT ('a', fileName); }
void processT (char *fileName) { processAorT ('t', fileName); |
(not something I would advise, by the way).
Having said that, I'm not sure what you're proposing is a good idea anyway.
The compiler may be able to detect invalid constants, but won't be very successful if the parameter passed into IOnlyAcceptPrimeNumbers has come from a variable or, worse, input by a user.
The API is a contract between caller and function and, if the rules of that contract are not followed, you're free to do whatever you want, though hopefully you'd document it.
In other words, that function should begin:
void IOnlyAcceptPrimeNumbers (int num) {
if (!isPrime (num)) return;
// do something with a prime number.
}
(or the equivalent for your function that accepts a and t but not x). Doing nothing when passed invalid parameters is a reasonable strategy, as is returning an error or throwing an exception (though no doubt some would argue with this).
How you handle it is up to you, but it needs to be handled at runtime simply because the compiler doesn't have all the information.
You can only check value validity at runtime. Best you can do is use assert to stop programm execution if precondition is violated.
No. If you want to restrict the accepted arguments you need to use enums or accept an object that inherits from a specific interface (depends how sophisticated you want to make it). Enums is the common way to address this issue.
The example about the IOnlyAcceptPrimeNumbers is not well designed. If you want to achieve something similar it would be better to provide a class method that is something such as bool setNumber(int number) that will return false if the number is not prime. If you want to do it in the costructor the real alternative is to throw an exception (that is not really nice to do).
The concept is that you can not simply rely that the user will pass you only elements from a (correct) subset of the values that the parameter type allows.
While more restrictive than your requirements (this limits the values a particular type can hold), you can always try something like:
// Vowel.h
#ifndef VOWEL_H_
#define VOWEL_H_
class Vowel
{
public:
static const Vowel A;
static const Vowel E;
static const Vowel I;
static const Vowel O;
static const Vowel U;
char get() const { return value; }
private:
explicit Vowel(char c);
char value;
};
#endif /* VOWEL_H_ */
// Vowel.cpp
#include "Vowel.h"
Vowel::Vowel(char c) : value(c) {}
const Vowel Vowel::A('A');
const Vowel Vowel::E('E');
const Vowel Vowel::I('I');
const Vowel Vowel::O('O');
const Vowel Vowel::U('U');
Since the char constructor is private, only Vowel itself can construct objects from chars. All other uses are done by copy construction or copy assignment.
(I think I originally learned this technique from Scott Meyers; thank him / blame me.)