C Program Compile Error: Undefined reference to function 'compare'? - c

Here is my code:
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
main()
{
int x,y;
x = 2, y = 1;
printf("%d", compare(x,y));
int compare(int a, int b)
{
int returnValue = 0;
if(a>b)
returnValue = 1;
else if(a<b)
returnValue = -1;
else
returnValue = 0;
return(returnValue);
}
}
And this is the compiler error that I recieve:
In function `main':
asdf.c:(.text+0x21): undefined reference to `compare'
collect2: error: ld returned 1 exit status
I have looked into this problem, and every question that I can find with this error is because people are importing functions from different files. These two functions are in the same file, and the compare() function is declared before the main(). I would appreciate any help as to why I am getting this error.
Thank you for your time.

You must define function outside the main function.
your code should be:
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
main()
{
int x,y;
x = 2, y = 1;
printf("%d", compare(x,y));
}
int compare(int a, int b)
{
int returnValue = 0;
if(a>b)
returnValue = 1;
else if(a<b)
returnValue = -1;
else
returnValue = 0;
return(returnValue);
}

The function compare must be out side the main program. Either you define the function header before the main() and have the function after the main or have the function before the main().
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
main()
{
int x,y;
x = 2, y = 1;
printf("%d", compare(x,y));
}
int compare(int a, int b)
{
int returnValue = 0;
if(a>b)
returnValue = 1;
else if(a<b)
returnValue = -1;
else
returnValue = 0;
return returnValue;
}

Nested function does not exist in C. But again speaking that it's a compiler specific
You can see gcc extension for nested function which is nonstandard.
So for solution simply move your function definition to outside the main.

You've declared the global function compare at file scope, but only defined a nested function main::compare. As commenters have pointed out, this is not standard C, it's a gcc extension that you don't want to be using.
Move compare out to file scope:
int main()
{
// do stuff
return 0;
}
int compare(int a, int b)
{
// do stuff
return value;
}

Put compare function out of main function. C language doesn't allow functions defined inside other functions.
Code
#include <stdio.h>
#include <stdlib.h>
int compare(int a, int b);
int main(void )
{
int x,y;
x = 2, y = 1;
printf("%d\n", compare(x,y));
}
int compare(int a, int b)
{
return ((a<b) - (a>b));
}

You have two different functions compare: One at global scope, which is only declared, but not defined, and one defined at local scope. The local compare can only be called from local scope, but only after it is defined. (Declaring a nested function inside the body of main before its definition doesn't work, because the C standard permits declarations in function bodies, but treats them as global.)
If you must use nested functions, move the definition of your local compare to the beginning of main. Nested functions are non-standard.
It is better to move the definition of compare outside the function into file scope. If you keep the definition of compare close to where it's called and make it static, you will get the same behaviour.

Related

Auto VS Static Variable Scope in C programming

Helloo!! I am currently learning about variable scope in C programming, auto, static and extern. I am running this code below and I am not sure why it works. I thought auto variables are only defined in the function it is defined in and does not retain its value? How is it that this code is working? Shouldn't the int a,b be static variables instead?
#include <stdio.h>
void sum(void)
{
auto int a,b;
a = 91; b = 7;
printf("%d + %d = %d\n",a,b,a+b);
}
int main()
{
puts("Calling the sum() function:");
sum();
puts("done");
return(0);
}
Your variables are not retaining anything. They're always the same value because you're explicitly assigning them the same values in sum().
a = 91; b = 7;
If you change your code to accept the variables as parameters instead, you'll get the output you would expect.
#include <stdio.h>
void sum(int a, int b)
{
printf("%d + %d = %d\n",a,b,a+b);
}
int main()
{
puts("Calling the sum() function:");
sum(91, 7);
sum(23, 9);
auto int x = 44;
auto int y = 24;
sum(x, y);
puts("done");
return(0);
}
If you try to access x or y from within sum() now, you'll get an error that they aren't in scope.

Passing function to function C [duplicate]

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}

Using variables

I have a problem with this simple program because it doesnt give me the true outcome. I just want to sum two arguments in the first function and then use the outcome in the second one. It will be nice to have overall outcome in the main function. Also I would like to ask the same question with arrays.
#include <stdio.h>
#include <stdlib.h>
int sum()
{
int a=2;
int b=3;
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int s)
{
int c=5;
int d=c+s;
}
int main(int s,int d)
{
sum();
printf("sum=%d\n",s);
printf("sum2=%d\n",d);
getchar();
return 0;
}
There are many problems with this code:
int main(int s, int d) won't do what you think. Command-line arguments to your program come in string format. So you would need to use int main(int argc, char *argv[]).
The variables s and d in main() are completely independent to the variables in sum() and sum2(). So changing their values in those functions will not affect the original variables.
You're not even calling the second function!
You can do things like this:
int sum(int a, int b)
{
return a+b;
}
int sum2(int c)
{
return c+5;
}
int main(void)
{
int x = 2;
int y = 3;
int z = sum(x,y);
int w = sum2(z);
printf("z = %d\n", z);
printf("w = %d\n", w);
}
First of all, s is a local variable inside sum( ). Hence it cannot be available outside the function.
int sum() {
// ..
int s = a+b; // local variable, hence local scope
// ..
}
Also, secondly, int main(int s,int d) won't work since in command line arguments come in String format. So can't use a int there
I won't tell you the answer (lol but others have) but I'll give you these clues to figuring it out.
Ask your self which functions are returning data and which ones aren't.
Clue: the function needs a return to return some data.
Then ask yourself which functions' returns are actually being used.
Clue: to collect the data returned from a function you need to assign the result to a variable like so
int i;
i = somefunct();
You can't access the value of variable 's' outside the function sum() since it is out of scope. You'll have to return the value to your main() function. Also your main function parameters are incorrect. You need something more like this:
#include <stdio.h>
#include <stdlib.h>
int sum(int a, int b)
{
int s=a+b;
printf("sum=%d\n",s);
return s;
}
int sum2(int c, int sum)
{
return c+sum;
}
int main(int argc, char *argv[])
{
int val1 = sum(2, 3);
printf("sum=%d\n",val1);
int val2 = sum2(5, val1);
printf("sum2=%d\n", val2);
getchar();
return 0;
}

What does "implicit declaration of function" mean?

#include <stdio.h>
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
int addNumbers(int a, int b)
{
return a + b;
}
Why does this not compile, I get a message saying implicit declaration of function addNumbers()?
Either define the function before main() or provide its prototype before main().
So either do this:
#include <stdio.h>
int addNumbers(int a, int b)
{ //definition
}
int main()
{ //Code in main
addNumbers(a, b);
}
or this:
#include <stdio.h>
int addNumbers(int, int);
int main()
{ //Code in main
addNumbers(a, b);
}
int addNumbers(int a, int b)
{ // definition
}
You need to declare the function before you call it in main(). Either move it before main or at least declare it there.
Also, you should prob add return 0 at the end of the main function since it's supposed to return int.
#include <stdio.h>
int addNumbers(int a, int b)
{
return a + b;
}
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
return 0;
}
You have to either move the entire addNumber() function above main or provide a prototype. The latter is done the following way:
int addNumbers(int a, int b);
int main()
{
// code of main() here
}
int addNumbers(int a, int b)
{
//code of addNumbers() here
}
Put addNumbers before main
int addNumbers(int a, int b)
{
return a + b;
}
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
UPDATE:
To print it, printf("%i",addNumbers(a, b)); will display 7 in above case.
You can move the whole function above the point where it is called, or use a function prototype, like this:
#include <stdio.h>
int addNumbers(int a, int b); // function prototype
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
int addNumbers(int a, int b)
{
return a + b;
}
You'll need a forward declaration of the addNumbers function or its definition moved up before the first usage:
// 2161304
#include <stdio.h>
// forward declaration
int addNumbers(int a, int b);
int main()
{
int a = 4;
int b = 3;
addNumbers(a, b);
}
// alternatively move this up before main ...
int addNumbers(int a, int b)
{
return a + b;
}
Regarding main and return:
Programs will compile without. The signatures of main defined by the standard are:
int main(void)
int main(int argc, char **argv)
There are three portable return values:
0, EXIT_SUCCESS, EXIT_FAILURE
which are defined in stdlib.h.
Declare the function before using it by either adding a prototype before main():
int addNumbers(int a, int b);
or move the whole addNumbers function before main().
I agree with declaration and definition thing but i am not getting any compilation errors with the above code.My gcc version is "4.4.1-4ubuntu9".Any ideas.
I have done a little modification to test the code.
#include <stdio.h>
int main()
{
int a = 4;
int b = 3;
printf("%d", addNumbers(a, b)); // Printf added.
}
int addNumbers(int a, int b)
{
return a + b;
}
You must declare the function before using.
Remember these 4 basic parts while dealing with functions.
Declaration
Call
Definition
Return
if your compiler is C99 standard it throws and error "implicit declaration", since since default promotion is obsolete in C99 standard.
if you try to compile with C89 standard this would be allowable.
In C99 standard function prototype is necessary
Since the compiler executes one line after another,by the time it sees the function call,it has to have the information about that function which the main function is calling.so my friend u need to tell the compiler about the function before you can ever use it.

How do you pass a function as a parameter in C?

I want to create a function that performs a function passed by parameter on a set of data. How do you pass a function as a parameter in C?
Declaration
A prototype for a function which takes a function parameter looks like the following:
void func ( void (*f)(int) );
This states that the parameter f will be a pointer to a function which has a void return type and which takes a single int parameter. The following function (print) is an example of a function which could be passed to func as a parameter because it is the proper type:
void print ( int x ) {
printf("%d\n", x);
}
Function Call
When calling a function with a function parameter, the value passed must be a pointer to a function. Use the function's name (without parentheses) for this:
func(print);
would call func, passing the print function to it.
Function Body
As with any parameter, func can now use the parameter's name in the function body to access the value of the parameter. Let's say that func will apply the function it is passed to the numbers 0-4. Consider, first, what the loop would look like to call print directly:
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
print(ctr);
}
Since func's parameter declaration says that f is the name for a pointer to the desired function, we recall first that if f is a pointer then *f is the thing that f points to (i.e. the function print in this case). As a result, just replace every occurrence of print in the loop above with *f:
void func ( void (*f)(int) ) {
for ( int ctr = 0 ; ctr < 5 ; ctr++ ) {
(*f)(ctr);
}
}
Source
This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.
typedef void (*functiontype)();
Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:
void dosomething() { }
functiontype func = &dosomething;
func();
For a function that returns an int and takes a char you would do
typedef int (*functiontype2)(char);
and to use it
int dosomethingwithchar(char a) { return 1; }
functiontype2 func2 = &dosomethingwithchar
int result = func2('a');
There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!
boost::function<int (char a)> functiontype2;
is so much nicer than the above.
Since C++11 you can use the functional library to do this in a succinct and generic fashion. The syntax is, e.g.,
std::function<bool (int)>
where bool is the return type here of a one-argument function whose first argument is of type int.
I have included an example program below:
// g++ test.cpp --std=c++11
#include <functional>
double Combiner(double a, double b, std::function<double (double,double)> func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Sometimes, though, it is more convenient to use a template function:
// g++ test.cpp --std=c++11
template<class T>
double Combiner(double a, double b, T func){
return func(a,b);
}
double Add(double a, double b){
return a+b;
}
double Mult(double a, double b){
return a*b;
}
int main(){
Combiner(12,13,Add);
Combiner(12,13,Mult);
}
Pass address of a function as parameter to another function as shown below
#include <stdio.h>
void print();
void execute(void());
int main()
{
execute(print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void f()) // receive address of print
{
f();
}
Also we can pass function as parameter using function pointer
#include <stdio.h>
void print();
void execute(void (*f)());
int main()
{
execute(&print); // sends address of print
return 0;
}
void print()
{
printf("Hello!");
}
void execute(void (*f)()) // receive address of print
{
f();
}
Functions can be "passed" as function pointers, as per ISO C11 6.7.6.3p8: "A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1. ". For example, this:
void foo(int bar(int, int));
is equivalent to this:
void foo(int (*bar)(int, int));
I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function.
Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.
Compare Function
bool compare(int a, int b) {
return a > b;
}
Now , the Bubble sort that takes another function as its parameter to perform comparison
Bubble sort function
void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {
for (int i = 0;i < n - 1;i++) {
for (int j = 0;j < (n - 1 - i);j++) {
if (cmp(arr[j], arr[j + 1])) {
swap(arr[j], arr[j + 1]);
}
}
}
}
Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.
int main()
{
int i, n = 10, key = 11;
int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };
bubble_sort(arr, n, compare);
cout<<"Sorted Order"<<endl;
for (int i = 0;i < n;i++) {
cout << arr[i] << " ";
}
}
Output:
Sorted Order
3 6 8 11 12 12 15 18 20 22
You need to pass a function pointer. The syntax is a little cumbersome, but it's really powerful once you get familiar with it.
typedef int function();
function *g(function *f)
{
f();
return f;
}
int main(void)
{
function f;
function *fn = g(f);
fn();
}
int f() { return 0; }
It's not really a function, but it is an localised piece of code. Of course it doesn't pass the code just the result. It won't work if passed to an event dispatcher to be run at a later time (as the result is calculated now and not when the event occurs). But it does localise your code into one place if that is all you are trying to do.
#include <stdio.h>
int IncMultInt(int a, int b)
{
a++;
return a * b;
}
int main(int argc, char *argv[])
{
int a = 5;
int b = 7;
printf("%d * %d = %d\n", a, b, IncMultInt(a, b));
b = 9;
// Create some local code with it's own local variable
printf("%d * %d = %d\n", a, b, ( { int _a = a+1; _a * b; } ) );
return 0;
}

Resources