I’ve read the EULA license and I have known that a game created with UE4 can’t be published as open source because this engine is closed-source.
I suppose that my game project will be made up of .cpp and .h files.
Can I publish only .cpp files so the headers that contain the engine classes won’t be distributed?
If I can do this, users won’t be able to build my game but they will be able to explore my code. This would also advertise UE because users will need this engine to modify my game and make their own ones.
Can I do this or is it illegal?
First off, with the usual caveat that I am not a lawyer and this doesn’t constitute legal advice, the EULA is the best place to start: EULA - Unreal Engine
You can publish any of your game code under a compatible license (MIT, BSD, zlib, etc…, but explicitly not GPL or LGPL), as long as it doesn’t fall into a couple of specific categories (modifications to engine code, copy-pasted engine code, etc…). If you only have game code and make no engine modifications, you should be fine. If you have engine modifications required to build your game, those can only be distributed to other licensees. The best mechanism we have for this currently is to distribute them only on a fork of the GitHub source, which as part of the private Epic organization is only visible to other licensees.
For example, Andrew’s project has the game source here GitHub - AndrewScheidecker/BrickGame: A demo of Minecraft-style voxel rendering in UE4 under a BSD license, visible to anyone, but his engine modifications are in a fork of the engine GitHub account here https://github.com/AndrewScheidecker/UnrealEngine/tree/BrickGame, visible only to subscribers.