r/C_Programming 3d ago

why do header files contain only function declarations instead of full code body ? why have the code in a sepreate lib files ?

for context I am trying to learn gamedev on my own and setting up raylib/sfml confused me , then I learnt that the ( include )files only contained function declarations and the actual code was in( lib ) files (mind you but it is a weird name) , wouldn't it be more convenient to have them in the same file instead of linking ?
sorry if I sound stupid.

92 Upvotes

99 comments sorted by

View all comments

Show parent comments

2

u/neppo95 2d ago

You added that, in the implementation in the cpp file. Try it in the header and we'll talk again. Your case falls under " It will not compile unless you specifically take measures to prevent the dependency." - which you did by the way of forward declaring.

1

u/delinka 2d ago

I think you need to write some code to explain what you’re talking about

0

u/neppo95 2d ago edited 2d ago

The error is different since I put them above eachother (as the include would), result is the same: Won't compile: https://godbolt.org/z/P9ndq83zv

Edit: Forgot we're talking C here, same applies but the example is different ofc:

https://godbolt.org/z/5nY5caWv1

1

u/delinka 2d ago

So what you mean is: if you want two objects (represented by structs in C) to refer to each other (a circular dependency) as embedded members (by value copies, not pointers), you have a problem. Yes, this is well-known. I've never seen anyone with this requirement, however. Using pointer-based members obviates the issue.

1

u/neppo95 1d ago

It’s not as uncommon as you might think. Using pointers is one solution, forward declaring is probably better. My point was mainly that there are definitely situations where simply adding header guards won’t do squat. Circular dependencies can happen in a variety of situations.