c++ - C: Using functions from files within in the same project -
my question not link direct example, more of question whole. when coding c++, found (after looking through threads) in order use functions different files in same project, either need header file. so, example, if have main function in file called "main.cpp" , wanted use function, "prob1()" in file called "problem1.cpp", need use header file.
what confusing me why not have worry programming in c? when programming in c, in order use functions different files, call function directly.
any help/explanation appreciated. thanks!
your c compiler can implicitly declare function, should doing yourself. if turn warnings, you'll see like:
file1.c: warning: implicit declaration of function ‘func_from_f2’ when file1.c being compiled, implicit declaration used create object file , when linking have hope function exist , declaration correct object files can linked successfully.
if not, linker give error somewhere along lines of:
undefined reference `func_from_f2'
don't need header file, can include declaration/prototype of function in source file (the #include directive you). ie. below work fine without warnings:
file1.c
void func_from_f2(void); int main(void) { func_from_f2(); return 0; } file2.c
#include <stdio.h> void func_from_f2(void) { puts("hello"); }
however, it's best practice use header file:
file1.c
#include "file2.h" int main(void) { func_from_f2(); return 0; } file2.h
#ifndef file2_h #define file2_h void func_from_f2(void); #endif file2.c
#include <stdio.h> #include "file2.h" void func_from_f2(void) { puts("hello"); }
Comments
Post a Comment