tags:

views:

409

answers:

4

I'm trying to learn C by writing a simple program to output Fibonacci numbers. It isn't working.

fibonacci.h

unsigned int fibonacci_recursive(unsigned int n);

fibonacci.c

#include <stdio.h>
#include "fibonacci.h"

main() {
    unsigned int i;
    for (i = 0; i < 10; i++) {
        printf("%d\t%n", fibonacci_recursive(i));
    }
    getchar();
}

fibonacci_recursive.c

unsigned int fib_rec(unsigned int n);

main(unsigned int n) {
     return fib_rec(n);
}

unsigned int fib_rec(unsigned int n) {
    if (n == 0) {
        return 0;
     } 
     if (n == 1) {
           return 1;
     }
     return fib_rec(n - 1) + fib_rec(n - 2);
}

This is the error message VS 2010 gives me when I try to build the project:

1>ClCompile:
1>  fibonacci_recursive.c
1>fibonacci_recursive.obj : error LNK2005: _main already defined in fibonacci.obj
1>fibonacci.obj : error LNK2019: unresolved external symbol _fibonacci_recursive referenced in function _main
1>c:\users\odp\documents\visual studio 2010\Projects\Fibonacci\Debug\Fibonacci.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.
1>

What am I doing wrong here? Thanks for helping someone new to C.

+3  A: 

You have the main() function defined twice in your project. This is the entry point of your program, and you only need one.

andri
+2  A: 

You haven't created a fibonacci_recursive function that you declared in fibonacci.h.

Tor Valamo
+4  A: 

Your approach seems strange, you should have:

  • a main file (example main.c) with the main method and that includes fibonacci.h
  • a fibonacci.h with the prototype unsigned int fibonacci_recursive(unsigned int n);
  • a fibonacci.c with the implementation of the method, and it should include fibonacci.h too

Actually you define main function twice too..

main.c

#include <stdio.h>
#include "fibonacci.h"

main()
{
    unsigned int i;
    for (i = 0; i < 10; i++)
    {
        printf("%d\t%n", fibonacci_recursive(i));
    }
    getchar();
}

fibonacci.h

unsigned int fibonacci_recursive(unsigned int n);

fibonacci.c

#include "fibonacci.h"
unsigned int fibonacci_recursive(unsigned int n)
{
    if (n == 0) 
    {
        return 0;
     } 
     if (n == 1) {
           return 1;
     }
     return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
Jack
Indeed. Thanks.
Rosarch
forgot to fix a typo, it was fib_rec.. I don't know way you used to way to name the same function :D
Jack
Another used deleted a post in which he pointed the fact that you are using **%n** inside the printf string. Change it with **\n**
Jack
+4  A: 

You need \n not %n for your printf. Also, you can simplify as:

#include "fibonacci.h"

unsigned int fibonacci_recursive(unsigned int n) {
if (n <= 2) 
    return n;
else
    return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2);
}
Ramashalanka