c & cpp

Hi all

could the compiling of c and cpp source files cause any problem durring the compiling, bualding and executing the program? .

thanks
Any functions you use that are defined in C source files (and compiled as C) must be
declared as extern "C" in the header file when the header file is included by a
cpp source file.

but i still have some questions

1- first, why should the c function declared as extern to be able to accessed form cpp source file?

2- second,that is really my main question, if i do define only function in the c source file and i include in the header file of it one cpp header, in which i have declared on class. So if i instantiate one object of this class in the another header and access this instance in the c file i get problem by linking the program. the error that i got is :

file.c: multiple definition of object

file.cpp: first definition

may someone clarify this problem?

thanks for suggestion
Last edited on
1. Because otherwise the C++ compiler will try to mangle the name. C names are unmangled, so when the linker tries to link everything, it will find undefined symbols.

2. What?
@helios : i correct the 2. question.
closed account (S6k9GNh0)
....It's because your making object file.<objectextension> twice. It doesn't know how to deal with it.

@computerquip

your right... but why doesn't the compiler know how to deal with the cpp header file if it was included twice? i have made the same error often. I need to understand the reason to avoid doing the same mistake each time i program?

could someone give me some informations about how the compile deal with including files?
Because files are included before a source is sent to the compiler, during the preprocessing stage. All the compiler sees is a single file without any preprocessor directives, so it can't tell whether something was included or always there.
To avoid problems when something it included twice, we use inclusion guards:
1
2
3
4
#ifndef HEADER_H
#define HEADER_H
//your header here
#endif 
Topic archived. No new replies allowed.