Miroslav Trninic
Miroslav Trninic

Reputation: 3455

import function in c using extern keywod

I am having problem with importing external function to a main c file.

Here is my minimal code:

/* main.c */

#include<stdio.h>
extern int func() 

int main(){
    extern int func();
}

/*external file with one function that I want to     
import*/

#include<stdio.h>

int func(){
    printf("Hello World Again\n");
}

I compile and run like this - gcc main.c and then ./a.out but nothing is happening. Any idea ?

Upvotes: 0

Views: 8127

Answers (4)

cdarke
cdarke

Reputation: 44364

Edits: question has changed.

extern is only used for external variables. You just need a prototype for the function.

#include <stdio.h>

void func(void);    /* <-- prototype */

int main(int argc, char * argv[])
{
    func();

    return 0;
}

void func(void){
    printf("Hello World Again\n");
}

Notice a few things. A prototype of int func() means no parameter checking in C - this is different to C++. Also, you are not returning anything from the function, so I replace it with void func(void)

Upvotes: 0

Raghu Srikanth Reddy
Raghu Srikanth Reddy

Reputation: 2711

You are just declaring again in main function..

you need to call the function to work..#include

extern int func() 

int main(){
    func();
}

/*external file with one function that I want to     
import*/

#include<stdio.h>

int func(){
    printf("Hello World Again\n");
}

Upvotes: 0

simonc
simonc

Reputation: 42175

You have to compile the file containing func also

gcc -Wall main.c external_file.c

(Note that the -Wall in the compiler command isn't absolutely necessary but is very good practice)

As noted by others, you also need to fix your code to call func rather than just re-declaring it.

Upvotes: 5

Alok Save
Alok Save

Reputation: 206546

Because you only declared the function, You never called it!

extern int func();

Declares a function. To call it you must have:

int main()
{
   func();
} 

Upvotes: 2

Related Questions