I can use the function ecrecover to verify a signature in the contract, but I want to know how to create a signature in the contract. What should I do?
You shouldn't want to.
There is a two-fold engineering dilemma.
The computationally-heavy work of creating a signature isn't well-suited to a platform where cost is proportional to work. There are workarounds, but ...
Anything a contract can do is replicable by everyone else. For example, the whole idea of a signature is that it proves knowledge of a secret only the signer should know - the private key. For a contract to perform this process, the contract would have to know the secret. If that is the case, then everyone knows the secret which renders a signature meaningless.
They don't need to
In most cases, what you want is to show that an action came from the contract. This is handled at a protocol level without the need for the contract to sign anything.
I might suggest reframing the question in terms of what needs to be proven because it's probably doable. The solution will not include the contract signing in the way that externally-owned accounts do it.
Hope it helps.