0

What is the difference between a normal function (Sololearn usual function) and an external function?

Firstly, I was just curious about this question so i asked chatgpt. But i am somewhat skeptical about its answer. Here is the discussion link: https://chatgpt.com/c/f96e26cc-e636-45f9-80b6-a87401a8bee9 If you also think the chatgpt's answer is incorrect, then please explain it to me.

7th Oct 2024, 9:41 AM
Celvien Kurniawan
Celvien Kurniawan - avatar
3 odpowiedzi
+ 2
We cannot see your personal chatGPT session. A standard function and extern function are the same. But sometimes you want to put code in different files but still use those functions in other files. To make sure file1.c can see functions written in file2.c, it needs to be declared. ChatGPT generated a sample for me. In this example, the displayMessage() function is in file1, while main() is in file2. When you compile your code, the compiler does not share definitions between files normally. You can use header files or you can put declarations in any files that use the shared function. This is a decent example because you could have written a displayMessage() function inside file2.c that did something different than the displayMessage() in file1.c. The compiler wants to know specifically, did you forget to write the function? Or are you using the function from somewhere else? When you compile, each file is compiled separately. Then you link the files together to make the executable. The linking process is where it sorts out local and externs. The compiler needs to know when it reads file2.c that you didn't just forget to define the function. // File1.c #include <stdio.h> void displayMessage() { // Function definition printf("Hello from File1!\n"); } // File2.c #include <stdio.h> extern void displayMessage(); // Function declaration using extern int main() { displayMessage(); // Calls the function from File1.c return 0; }
7th Oct 2024, 1:25 PM
Jerry Hobby
Jerry Hobby - avatar
0
Oh, sorry about that (broken link). Let me update it. https://chatgpt.com/share/6704120c-8fd0-8006-9963-3a9650309cdd
7th Oct 2024, 4:38 PM
Celvien Kurniawan
Celvien Kurniawan - avatar
0
Jerry Hobby then the use of "extern" keyword is to tell the compiler that the function displayMessage() is from another file. In this case from file 1, doesn't it? Also i have another question, does the use of "extern" keyword is mandatory? Because from my chatgpt response... It just optional and just for clarity.
7th Oct 2024, 4:47 PM
Celvien Kurniawan
Celvien Kurniawan - avatar